1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package org.apache.commons.httpclient;
31
32 import java.io.ByteArrayInputStream;
33 import java.io.ByteArrayOutputStream;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.InterruptedIOException;
37 import java.util.Collection;
38
39 import org.apache.commons.httpclient.auth.AuthState;
40 import org.apache.commons.httpclient.cookie.CookiePolicy;
41 import org.apache.commons.httpclient.cookie.CookieSpec;
42 import org.apache.commons.httpclient.cookie.MalformedCookieException;
43 import org.apache.commons.httpclient.params.HttpMethodParams;
44 import org.apache.commons.httpclient.protocol.Protocol;
45 import org.apache.commons.httpclient.util.EncodingUtil;
46 import org.apache.commons.httpclient.util.ExceptionUtil;
47 import org.apache.commons.logging.Log;
48 import org.apache.commons.logging.LogFactory;
49
50 /***
51 * An abstract base implementation of HttpMethod.
52 * <p>
53 * At minimum, subclasses will need to override:
54 * <ul>
55 * <li>{@link #getName} to return the approriate name for this method
56 * </li>
57 * </ul>
58 * </p>
59 *
60 * <p>
61 * When a method requires additional request headers, subclasses will typically
62 * want to override:
63 * <ul>
64 * <li>{@link #addRequestHeaders addRequestHeaders(HttpState,HttpConnection)}
65 * to write those headers
66 * </li>
67 * </ul>
68 * </p>
69 *
70 * <p>
71 * When a method expects specific response headers, subclasses may want to
72 * override:
73 * <ul>
74 * <li>{@link #processResponseHeaders processResponseHeaders(HttpState,HttpConnection)}
75 * to handle those headers
76 * </li>
77 * </ul>
78 * </p>
79 *
80 *
81 * @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
82 * @author Rodney Waldhoff
83 * @author Sean C. Sullivan
84 * @author <a href="mailto:dion@apache.org">dIon Gillard</a>
85 * @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
86 * @author <a href="mailto:dims@apache.org">Davanum Srinivas</a>
87 * @author Ortwin Glueck
88 * @author Eric Johnson
89 * @author Michael Becke
90 * @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
91 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
92 * @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
93 * @author Christian Kohlschuetter
94 *
95 * @version $Revision: 160334 $ $Date: 2005-04-06 17:46:10 -0400 (Wed, 06 Apr 2005) $
96 */
97 public abstract class HttpMethodBase implements HttpMethod {
98
99
100
101 /*** Log object for this class. */
102 private static final Log LOG = LogFactory.getLog(HttpMethodBase.class);
103
104
105
106 /*** Request headers, if any. */
107 private HeaderGroup requestHeaders = new HeaderGroup();
108
109 /*** The Status-Line from the response. */
110 private StatusLine statusLine = null;
111
112 /*** Response headers, if any. */
113 private HeaderGroup responseHeaders = new HeaderGroup();
114
115 /*** Response trailer headers, if any. */
116 private HeaderGroup responseTrailerHeaders = new HeaderGroup();
117
118 /*** Path of the HTTP method. */
119 private String path = null;
120
121 /*** Query string of the HTTP method, if any. */
122 private String queryString = null;
123
124 /*** The response body of the HTTP method, assuming it has not be
125 * intercepted by a sub-class. */
126 private InputStream responseStream = null;
127
128 /*** The connection that the response stream was read from. */
129 private HttpConnection responseConnection = null;
130
131 /*** Buffer for the response */
132 private byte[] responseBody = null;
133
134 /*** True if the HTTP method should automatically follow HTTP redirects.*/
135 private boolean followRedirects = false;
136
137 /*** True if the HTTP method should automatically handle
138 * HTTP authentication challenges. */
139 private boolean doAuthentication = true;
140
141 /*** HTTP protocol parameters. */
142 private HttpMethodParams params = new HttpMethodParams();
143
144 /*** Host authentication state */
145 private AuthState hostAuthState = new AuthState();
146
147 /*** Proxy authentication state */
148 private AuthState proxyAuthState = new AuthState();
149
150 /*** True if this method has already been executed. */
151 private boolean used = false;
152
153 /*** Count of how many times did this HTTP method transparently handle
154 * a recoverable exception. */
155 private int recoverableExceptionCount = 0;
156
157 /*** the host for this HTTP method, can be null */
158 private HttpHost httphost = null;
159
160 /***
161 * Handles method retries
162 *
163 * @deprecated no loner used
164 */
165 private MethodRetryHandler methodRetryHandler;
166
167 /*** True if the connection must be closed when no longer needed */
168 private boolean connectionCloseForced = false;
169
170 /*** Number of milliseconds to wait for 100-contunue response. */
171 private static final int RESPONSE_WAIT_TIME_MS = 3000;
172
173 /*** HTTP protocol version used for execution of this method. */
174 private HttpVersion effectiveVersion = null;
175
176 /*** Whether the execution of this method has been aborted */
177 private transient boolean aborted = false;
178
179 /*** Whether the HTTP request has been transmitted to the target
180 * server it its entirety */
181 private boolean requestSent = false;
182
183 /*** Actual cookie policy */
184 private CookieSpec cookiespec = null;
185
186 /*** Default initial size of the response buffer if content length is unknown. */
187 private static final int DEFAULT_INITIAL_BUFFER_SIZE = 4*1024;
188
189
190
191 /***
192 * No-arg constructor.
193 */
194 public HttpMethodBase() {
195 }
196
197 /***
198 * Constructor specifying a URI.
199 * It is responsibility of the caller to ensure that URI elements
200 * (path & query parameters) are properly encoded (URL safe).
201 *
202 * @param uri either an absolute or relative URI. The URI is expected
203 * to be URL-encoded
204 *
205 * @throws IllegalArgumentException when URI is invalid
206 * @throws IllegalStateException when protocol of the absolute URI is not recognised
207 */
208 public HttpMethodBase(String uri)
209 throws IllegalArgumentException, IllegalStateException {
210
211 try {
212
213
214 if (uri == null || uri.equals("")) {
215 uri = "/";
216 }
217 setURI(new URI(uri, true));
218 } catch (URIException e) {
219 throw new IllegalArgumentException("Invalid uri '"
220 + uri + "': " + e.getMessage()
221 );
222 }
223 }
224
225
226
227 /***
228 * Obtains the name of the HTTP method as used in the HTTP request line,
229 * for example <tt>"GET"</tt> or <tt>"POST"</tt>.
230 *
231 * @return the name of this method
232 */
233 public abstract String getName();
234
235 /***
236 * Returns the URI of the HTTP method
237 *
238 * @return The URI
239 *
240 * @throws URIException If the URI cannot be created.
241 *
242 * @see org.apache.commons.httpclient.HttpMethod#getURI()
243 */
244 public URI getURI() throws URIException {
245 StringBuffer buffer = new StringBuffer();
246 if (this.httphost != null) {
247 buffer.append(this.httphost.getProtocol().getScheme());
248 buffer.append("://");
249 buffer.append(this.httphost.getHostName());
250 int port = this.httphost.getPort();
251 if (port != -1 && port != this.httphost.getProtocol().getDefaultPort()) {
252 buffer.append(":");
253 buffer.append(port);
254 }
255 }
256 buffer.append(this.path);
257 if (this.queryString != null) {
258 buffer.append('?');
259 buffer.append(this.queryString);
260 }
261 return new URI(buffer.toString(), true);
262 }
263
264 /***
265 * Sets the URI for this method.
266 *
267 * @param uri URI to be set
268 *
269 * @throws URIException if a URI cannot be set
270 *
271 * @since 3.0
272 */
273 public void setURI(URI uri) throws URIException {
274
275 if (uri.isAbsoluteURI()) {
276 this.httphost = new HttpHost(uri);
277 }
278
279 setPath(
280 uri.getPath() == null
281 ? "/"
282 : uri.getEscapedPath()
283 );
284 setQueryString(uri.getEscapedQuery());
285 }
286
287 /***
288 * Sets whether or not the HTTP method should automatically follow HTTP redirects
289 * (status code 302, etc.)
290 *
291 * @param followRedirects <tt>true</tt> if the method will automatically follow redirects,
292 * <tt>false</tt> otherwise.
293 */
294 public void setFollowRedirects(boolean followRedirects) {
295 this.followRedirects = followRedirects;
296 }
297
298 /***
299 * Returns <tt>true</tt> if the HTTP method should automatically follow HTTP redirects
300 * (status code 302, etc.), <tt>false</tt> otherwise.
301 *
302 * @return <tt>true</tt> if the method will automatically follow HTTP redirects,
303 * <tt>false</tt> otherwise.
304 */
305 public boolean getFollowRedirects() {
306 return this.followRedirects;
307 }
308
309 /*** Sets whether version 1.1 of the HTTP protocol should be used per default.
310 *
311 * @param http11 <tt>true</tt> to use HTTP/1.1, <tt>false</tt> to use 1.0
312 *
313 * @deprecated Use {@link HttpMethodParams#setVersion(HttpVersion)}
314 */
315 public void setHttp11(boolean http11) {
316 if (http11) {
317 this.params.setVersion(HttpVersion.HTTP_1_1);
318 } else {
319 this.params.setVersion(HttpVersion.HTTP_1_0);
320 }
321 }
322
323 /***
324 * Returns <tt>true</tt> if the HTTP method should automatically handle HTTP
325 * authentication challenges (status code 401, etc.), <tt>false</tt> otherwise
326 *
327 * @return <tt>true</tt> if authentication challenges will be processed
328 * automatically, <tt>false</tt> otherwise.
329 *
330 * @since 2.0
331 */
332 public boolean getDoAuthentication() {
333 return doAuthentication;
334 }
335
336 /***
337 * Sets whether or not the HTTP method should automatically handle HTTP
338 * authentication challenges (status code 401, etc.)
339 *
340 * @param doAuthentication <tt>true</tt> to process authentication challenges
341 * authomatically, <tt>false</tt> otherwise.
342 *
343 * @since 2.0
344 */
345 public void setDoAuthentication(boolean doAuthentication) {
346 this.doAuthentication = doAuthentication;
347 }
348
349
350
351 /***
352 * Returns <tt>true</tt> if version 1.1 of the HTTP protocol should be
353 * used per default, <tt>false</tt> if version 1.0 should be used.
354 *
355 * @return <tt>true</tt> to use HTTP/1.1, <tt>false</tt> to use 1.0
356 *
357 * @deprecated Use {@link HttpMethodParams#getVersion()}
358 */
359 public boolean isHttp11() {
360 return this.params.getVersion().equals(HttpVersion.HTTP_1_1);
361 }
362
363 /***
364 * Sets the path of the HTTP method.
365 * It is responsibility of the caller to ensure that the path is
366 * properly encoded (URL safe).
367 *
368 * @param path the path of the HTTP method. The path is expected
369 * to be URL-encoded
370 */
371 public void setPath(String path) {
372 this.path = path;
373 }
374
375 /***
376 * Adds the specified request header, NOT overwriting any previous value.
377 * Note that header-name matching is case insensitive.
378 *
379 * @param header the header to add to the request
380 */
381 public void addRequestHeader(Header header) {
382 LOG.trace("HttpMethodBase.addRequestHeader(Header)");
383
384 if (header == null) {
385 LOG.debug("null header value ignored");
386 } else {
387 getRequestHeaderGroup().addHeader(header);
388 }
389 }
390
391 /***
392 * Use this method internally to add footers.
393 *
394 * @param footer The footer to add.
395 */
396 public void addResponseFooter(Header footer) {
397 getResponseTrailerHeaderGroup().addHeader(footer);
398 }
399
400 /***
401 * Gets the path of this HTTP method.
402 * Calling this method <em>after</em> the request has been executed will
403 * return the <em>actual</em> path, following any redirects automatically
404 * handled by this HTTP method.
405 *
406 * @return the path to request or "/" if the path is blank.
407 */
408 public String getPath() {
409 return (path == null || path.equals("")) ? "/" : path;
410 }
411
412 /***
413 * Sets the query string of this HTTP method. The caller must ensure that the string
414 * is properly URL encoded. The query string should not start with the question
415 * mark character.
416 *
417 * @param queryString the query string
418 *
419 * @see EncodingUtil#formUrlEncode(NameValuePair[], String)
420 */
421 public void setQueryString(String queryString) {
422 this.queryString = queryString;
423 }
424
425 /***
426 * Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters.
427 * To use a different charset the parameters can be encoded manually using EncodingUtil
428 * and set as a single String.
429 *
430 * @param params an array of {@link NameValuePair}s to add as query string
431 * parameters. The name/value pairs will be automcatically
432 * URL encoded
433 *
434 * @see EncodingUtil#formUrlEncode(NameValuePair[], String)
435 * @see #setQueryString(String)
436 */
437 public void setQueryString(NameValuePair[] params) {
438 LOG.trace("enter HttpMethodBase.setQueryString(NameValuePair[])");
439 queryString = EncodingUtil.formUrlEncode(params, "UTF-8");
440 }
441
442 /***
443 * Gets the query string of this HTTP method.
444 *
445 * @return The query string
446 */
447 public String getQueryString() {
448 return queryString;
449 }
450
451 /***
452 * Set the specified request header, overwriting any previous value. Note
453 * that header-name matching is case-insensitive.
454 *
455 * @param headerName the header's name
456 * @param headerValue the header's value
457 */
458 public void setRequestHeader(String headerName, String headerValue) {
459 Header header = new Header(headerName, headerValue);
460 setRequestHeader(header);
461 }
462
463 /***
464 * Sets the specified request header, overwriting any previous value.
465 * Note that header-name matching is case insensitive.
466 *
467 * @param header the header
468 */
469 public void setRequestHeader(Header header) {
470
471 Header[] headers = getRequestHeaderGroup().getHeaders(header.getName());
472
473 for (int i = 0; i < headers.length; i++) {
474 getRequestHeaderGroup().removeHeader(headers[i]);
475 }
476
477 getRequestHeaderGroup().addHeader(header);
478
479 }
480
481 /***
482 * Returns the specified request header. Note that header-name matching is
483 * case insensitive. <tt>null</tt> will be returned if either
484 * <i>headerName</i> is <tt>null</tt> or there is no matching header for
485 * <i>headerName</i>.
486 *
487 * @param headerName The name of the header to be returned.
488 *
489 * @return The specified request header.
490 *
491 * @since 3.0
492 */
493 public Header getRequestHeader(String headerName) {
494 if (headerName == null) {
495 return null;
496 } else {
497 return getRequestHeaderGroup().getCondensedHeader(headerName);
498 }
499 }
500
501 /***
502 * Returns an array of the requests headers that the HTTP method currently has
503 *
504 * @return an array of my request headers.
505 */
506 public Header[] getRequestHeaders() {
507 return getRequestHeaderGroup().getAllHeaders();
508 }
509
510 /***
511 * @see org.apache.commons.httpclient.HttpMethod#getRequestHeaders(java.lang.String)
512 */
513 public Header[] getRequestHeaders(String headerName) {
514 return getRequestHeaderGroup().getHeaders(headerName);
515 }
516
517 /***
518 * Gets the {@link HeaderGroup header group} storing the request headers.
519 *
520 * @return a HeaderGroup
521 *
522 * @since 2.0beta1
523 */
524 protected HeaderGroup getRequestHeaderGroup() {
525 return requestHeaders;
526 }
527
528 /***
529 * Gets the {@link HeaderGroup header group} storing the response trailer headers
530 * as per RFC 2616 section 3.6.1.
531 *
532 * @return a HeaderGroup
533 *
534 * @since 2.0beta1
535 */
536 protected HeaderGroup getResponseTrailerHeaderGroup() {
537 return responseTrailerHeaders;
538 }
539
540 /***
541 * Gets the {@link HeaderGroup header group} storing the response headers.
542 *
543 * @return a HeaderGroup
544 *
545 * @since 2.0beta1
546 */
547 protected HeaderGroup getResponseHeaderGroup() {
548 return responseHeaders;
549 }
550
551 /***
552 * @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders(java.lang.String)
553 *
554 * @since 3.0
555 */
556 public Header[] getResponseHeaders(String headerName) {
557 return getResponseHeaderGroup().getHeaders(headerName);
558 }
559
560 /***
561 * Returns the response status code.
562 *
563 * @return the status code associated with the latest response.
564 */
565 public int getStatusCode() {
566 return statusLine.getStatusCode();
567 }
568
569 /***
570 * Provides access to the response status line.
571 *
572 * @return the status line object from the latest response.
573 * @since 2.0
574 */
575 public StatusLine getStatusLine() {
576 return statusLine;
577 }
578
579 /***
580 * Checks if response data is available.
581 * @return <tt>true</tt> if response data is available, <tt>false</tt> otherwise.
582 */
583 private boolean responseAvailable() {
584 return (responseBody != null) || (responseStream != null);
585 }
586
587 /***
588 * Returns an array of the response headers that the HTTP method currently has
589 * in the order in which they were read.
590 *
591 * @return an array of response headers.
592 */
593 public Header[] getResponseHeaders() {
594 return getResponseHeaderGroup().getAllHeaders();
595 }
596
597 /***
598 * Gets the response header associated with the given name. Header name
599 * matching is case insensitive. <tt>null</tt> will be returned if either
600 * <i>headerName</i> is <tt>null</tt> or there is no matching header for
601 * <i>headerName</i>.
602 *
603 * @param headerName the header name to match
604 *
605 * @return the matching header
606 */
607 public Header getResponseHeader(String headerName) {
608 if (headerName == null) {
609 return null;
610 } else {
611 return getResponseHeaderGroup().getCondensedHeader(headerName);
612 }
613 }
614
615
616 /***
617 * Return the length (in bytes) of the response body, as specified in a
618 * <tt>Content-Length</tt> header.
619 *
620 * <p>
621 * Return <tt>-1</tt> when the content-length is unknown.
622 * </p>
623 *
624 * @return content length, if <tt>Content-Length</tt> header is available.
625 * <tt>0</tt> indicates that the request has no body.
626 * If <tt>Content-Length</tt> header is not present, the method
627 * returns <tt>-1</tt>.
628 */
629 public long getResponseContentLength() {
630 Header[] headers = getResponseHeaderGroup().getHeaders("Content-Length");
631 if (headers.length == 0) {
632 return -1;
633 }
634 if (headers.length > 1) {
635 LOG.warn("Multiple content-length headers detected");
636 }
637 for (int i = headers.length - 1; i >= 0; i--) {
638 Header header = headers[i];
639 try {
640 return Long.parseLong(header.getValue());
641 } catch (NumberFormatException e) {
642 if (LOG.isWarnEnabled()) {
643 LOG.warn("Invalid content-length value: " + e.getMessage());
644 }
645 }
646
647 }
648 return -1;
649 }
650
651
652 /***
653 * Returns the response body of the HTTP method, if any, as an array of bytes.
654 * If response body is not available or cannot be read, returns <tt>null</tt>
655 *
656 * Note: This will cause the entire response body to be buffered in memory. A
657 * malicious server may easily exhaust all the VM memory. It is strongly
658 * recommended, to use getResponseAsStream if the content length of the response
659 * is unknown or resonably large.
660 *
661 * @return The response body.
662 *
663 * @throws IOException If an I/O (transport) problem occurs while obtaining the
664 * response body.
665 */
666 public byte[] getResponseBody() throws IOException {
667 if (this.responseBody == null) {
668 InputStream instream = getResponseBodyAsStream();
669 if (instream != null) {
670 long contentLength = getResponseContentLength();
671 if (contentLength > Integer.MAX_VALUE) {
672 throw new IOException("Content too large to be buffered: "+ contentLength +" bytes");
673 }
674 int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024);
675 if ((contentLength == -1) || (contentLength > limit)) {
676 LOG.warn("Going to buffer response body of large or unknown size. "
677 +"Using getResponseAsStream instead is recommended.");
678 }
679 LOG.debug("Buffering response body");
680 ByteArrayOutputStream outstream = new ByteArrayOutputStream(
681 contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
682 byte[] buffer = new byte[4096];
683 int len;
684 while ((len = instream.read(buffer)) > 0) {
685 outstream.write(buffer, 0, len);
686 }
687 outstream.close();
688 setResponseStream(null);
689 this.responseBody = outstream.toByteArray();
690 }
691 }
692 return this.responseBody;
693 }
694
695 /***
696 * Returns the response body of the HTTP method, if any, as an {@link InputStream}.
697 * If response body is not available, returns <tt>null</tt>
698 *
699 * @return The response body
700 *
701 * @throws IOException If an I/O (transport) problem occurs while obtaining the
702 * response body.
703 */
704 public InputStream getResponseBodyAsStream() throws IOException {
705 if (responseStream != null) {
706 return responseStream;
707 }
708 if (responseBody != null) {
709 InputStream byteResponseStream = new ByteArrayInputStream(responseBody);
710 LOG.debug("re-creating response stream from byte array");
711 return byteResponseStream;
712 }
713 return null;
714 }
715
716 /***
717 * Returns the response body of the HTTP method, if any, as a {@link String}.
718 * If response body is not available or cannot be read, returns <tt>null</tt>
719 * The string conversion on the data is done using the character encoding specified
720 * in <tt>Content-Type</tt> header.
721 *
722 * Note: This will cause the entire response body to be buffered in memory. A
723 * malicious server may easily exhaust all the VM memory. It is strongly
724 * recommended, to use getResponseAsStream if the content length of the response
725 * is unknown or resonably large.
726 *
727 * @return The response body.
728 *
729 * @throws IOException If an I/O (transport) problem occurs while obtaining the
730 * response body.
731 */
732 public String getResponseBodyAsString() throws IOException {
733 byte[] rawdata = null;
734 if (responseAvailable()) {
735 rawdata = getResponseBody();
736 }
737 if (rawdata != null) {
738 return EncodingUtil.getString(rawdata, getResponseCharSet());
739 } else {
740 return null;
741 }
742 }
743
744 /***
745 * Returns an array of the response footers that the HTTP method currently has
746 * in the order in which they were read.
747 *
748 * @return an array of footers
749 */
750 public Header[] getResponseFooters() {
751 return getResponseTrailerHeaderGroup().getAllHeaders();
752 }
753
754 /***
755 * Gets the response footer associated with the given name.
756 * Footer name matching is case insensitive.
757 * <tt>null</tt> will be returned if either <i>footerName</i> is
758 * <tt>null</tt> or there is no matching footer for <i>footerName</i>
759 * or there are no footers available. If there are multiple footers
760 * with the same name, there values will be combined with the ',' separator
761 * as specified by RFC2616.
762 *
763 * @param footerName the footer name to match
764 * @return the matching footer
765 */
766 public Header getResponseFooter(String footerName) {
767 if (footerName == null) {
768 return null;
769 } else {
770 return getResponseTrailerHeaderGroup().getCondensedHeader(footerName);
771 }
772 }
773
774 /***
775 * Sets the response stream.
776 * @param responseStream The new response stream.
777 */
778 protected void setResponseStream(InputStream responseStream) {
779 this.responseStream = responseStream;
780 }
781
782 /***
783 * Returns a stream from which the body of the current response may be read.
784 * If the method has not yet been executed, if <code>responseBodyConsumed</code>
785 * has been called, or if the stream returned by a previous call has been closed,
786 * <code>null</code> will be returned.
787 *
788 * @return the current response stream
789 */
790 protected InputStream getResponseStream() {
791 return responseStream;
792 }
793
794 /***
795 * Returns the status text (or "reason phrase") associated with the latest
796 * response.
797 *
798 * @return The status text.
799 */
800 public String getStatusText() {
801 return statusLine.getReasonPhrase();
802 }
803
804 /***
805 * Defines how strictly HttpClient follows the HTTP protocol specification
806 * (RFC 2616 and other relevant RFCs). In the strict mode HttpClient precisely
807 * implements the requirements of the specification, whereas in non-strict mode
808 * it attempts to mimic the exact behaviour of commonly used HTTP agents,
809 * which many HTTP servers expect.
810 *
811 * @param strictMode <tt>true</tt> for strict mode, <tt>false</tt> otherwise
812 *
813 * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
814 * to exercise a more granular control over HTTP protocol strictness.
815 */
816 public void setStrictMode(boolean strictMode) {
817 if (strictMode) {
818 this.params.makeStrict();
819 } else {
820 this.params.makeLenient();
821 }
822 }
823
824 /***
825 * @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
826 * to exercise a more granular control over HTTP protocol strictness.
827 *
828 * @return <tt>false</tt>
829 */
830 public boolean isStrictMode() {
831 return false;
832 }
833
834 /***
835 * Adds the specified request header, NOT overwriting any previous value.
836 * Note that header-name matching is case insensitive.
837 *
838 * @param headerName the header's name
839 * @param headerValue the header's value
840 */
841 public void addRequestHeader(String headerName, String headerValue) {
842 addRequestHeader(new Header(headerName, headerValue));
843 }
844
845 /***
846 * Tests if the connection should be force-closed when no longer needed.
847 *
848 * @return <code>true</code> if the connection must be closed
849 */
850 protected boolean isConnectionCloseForced() {
851 return this.connectionCloseForced;
852 }
853
854 /***
855 * Sets whether or not the connection should be force-closed when no longer
856 * needed. This value should only be set to <code>true</code> in abnormal
857 * circumstances, such as HTTP protocol violations.
858 *
859 * @param b <code>true</code> if the connection must be closed, <code>false</code>
860 * otherwise.
861 */
862 protected void setConnectionCloseForced(boolean b) {
863 if (LOG.isDebugEnabled()) {
864 LOG.debug("Force-close connection: " + b);
865 }
866 this.connectionCloseForced = b;
867 }
868
869 /***
870 * Tests if the connection should be closed after the method has been executed.
871 * The connection will be left open when using HTTP/1.1 or if <tt>Connection:
872 * keep-alive</tt> header was sent.
873 *
874 * @param conn the connection in question
875 *
876 * @return boolean true if we should close the connection.
877 */
878 protected boolean shouldCloseConnection(HttpConnection conn) {
879
880 if (isConnectionCloseForced()) {
881 LOG.debug("Should force-close connection.");
882 return true;
883 }
884
885 Header connectionHeader = null;
886
887 if (!conn.isTransparent()) {
888
889 connectionHeader = responseHeaders.getFirstHeader("proxy-connection");
890 }
891
892
893
894 if (connectionHeader == null) {
895 connectionHeader = responseHeaders.getFirstHeader("connection");
896 }
897
898
899 if (connectionHeader == null) {
900 connectionHeader = requestHeaders.getFirstHeader("connection");
901 }
902 if (connectionHeader != null) {
903 if (connectionHeader.getValue().equalsIgnoreCase("close")) {
904 if (LOG.isDebugEnabled()) {
905 LOG.debug("Should close connection in response to directive: "
906 + connectionHeader.getValue());
907 }
908 return true;
909 } else if (connectionHeader.getValue().equalsIgnoreCase("keep-alive")) {
910 if (LOG.isDebugEnabled()) {
911 LOG.debug("Should NOT close connection in response to directive: "
912 + connectionHeader.getValue());
913 }
914 return false;
915 } else {
916 if (LOG.isDebugEnabled()) {
917 LOG.debug("Unknown directive: " + connectionHeader.toExternalForm());
918 }
919 }
920 }
921 LOG.debug("Resorting to protocol version default close connection policy");
922
923 if (this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
924 if (LOG.isDebugEnabled()) {
925 LOG.debug("Should NOT close connection, using " + this.effectiveVersion.toString());
926 }
927 } else {
928 if (LOG.isDebugEnabled()) {
929 LOG.debug("Should close connection, using " + this.effectiveVersion.toString());
930 }
931 }
932 return this.effectiveVersion.lessEquals(HttpVersion.HTTP_1_0);
933 }
934
935 /***
936 * Tests if the this method is ready to be executed.
937 *
938 * @param state the {@link HttpState state} information associated with this method
939 * @param conn the {@link HttpConnection connection} to be used
940 * @throws HttpException If the method is in invalid state.
941 */
942 private void checkExecuteConditions(HttpState state, HttpConnection conn)
943 throws HttpException {
944
945 if (state == null) {
946 throw new IllegalArgumentException("HttpState parameter may not be null");
947 }
948 if (conn == null) {
949 throw new IllegalArgumentException("HttpConnection parameter may not be null");
950 }
951 if (this.aborted) {
952 throw new IllegalStateException("Method has been aborted");
953 }
954 if (!validate()) {
955 throw new ProtocolException("HttpMethodBase object not valid");
956 }
957 }
958
959 /***
960 * Executes this method using the specified <code>HttpConnection</code> and
961 * <code>HttpState</code>.
962 *
963 * @param state {@link HttpState state} information to associate with this
964 * request. Must be non-null.
965 * @param conn the {@link HttpConnection connection} to used to execute
966 * this HTTP method. Must be non-null.
967 *
968 * @return the integer status code if one was obtained, or <tt>-1</tt>
969 *
970 * @throws IOException if an I/O (transport) error occurs
971 * @throws HttpException if a protocol exception occurs.
972 */
973 public int execute(HttpState state, HttpConnection conn)
974 throws HttpException, IOException {
975
976 LOG.trace("enter HttpMethodBase.execute(HttpState, HttpConnection)");
977
978
979
980 this.responseConnection = conn;
981
982 checkExecuteConditions(state, conn);
983 this.statusLine = null;
984 this.connectionCloseForced = false;
985
986 conn.setLastResponseInputStream(null);
987
988
989 if (this.effectiveVersion == null) {
990 this.effectiveVersion = this.params.getVersion();
991 }
992
993 writeRequest(state, conn);
994 this.requestSent = true;
995 readResponse(state, conn);
996
997 used = true;
998
999 return statusLine.getStatusCode();
1000 }
1001
1002 /***
1003 * Aborts the execution of this method.
1004 *
1005 * @since 3.0
1006 */
1007 public void abort() {
1008 if (this.aborted) {
1009 return;
1010 }
1011 this.aborted = true;
1012 HttpConnection conn = this.responseConnection;
1013 if (conn != null) {
1014 conn.close();
1015 }
1016 }
1017
1018 /***
1019 * Returns <tt>true</tt> if the HTTP method has been already {@link #execute executed},
1020 * but not {@link #recycle recycled}.
1021 *
1022 * @return <tt>true</tt> if the method has been executed, <tt>false</tt> otherwise
1023 */
1024 public boolean hasBeenUsed() {
1025 return used;
1026 }
1027
1028 /***
1029 * Recycles the HTTP method so that it can be used again.
1030 * Note that all of the instance variables will be reset
1031 * once this method has been called. This method will also
1032 * release the connection being used by this HTTP method.
1033 *
1034 * @see #releaseConnection()
1035 *
1036 * @deprecated no longer supported and will be removed in the future
1037 * version of HttpClient
1038 */
1039 public void recycle() {
1040 LOG.trace("enter HttpMethodBase.recycle()");
1041
1042 releaseConnection();
1043
1044 path = null;
1045 followRedirects = false;
1046 doAuthentication = true;
1047 queryString = null;
1048 getRequestHeaderGroup().clear();
1049 getResponseHeaderGroup().clear();
1050 getResponseTrailerHeaderGroup().clear();
1051 statusLine = null;
1052 effectiveVersion = null;
1053 aborted = false;
1054 used = false;
1055 params = new HttpMethodParams();
1056 responseBody = null;
1057 recoverableExceptionCount = 0;
1058 connectionCloseForced = false;
1059 hostAuthState.invalidate();
1060 proxyAuthState.invalidate();
1061 cookiespec = null;
1062 requestSent = false;
1063 }
1064
1065 /***
1066 * Releases the connection being used by this HTTP method. In particular the
1067 * connection is used to read the response(if there is one) and will be held
1068 * until the response has been read. If the connection can be reused by other
1069 * HTTP methods it is NOT closed at this point.
1070 *
1071 * @since 2.0
1072 */
1073 public void releaseConnection() {
1074
1075 if (responseStream != null) {
1076 try {
1077
1078 responseStream.close();
1079 } catch (IOException e) {
1080
1081 ensureConnectionRelease();
1082 }
1083 } else {
1084
1085
1086
1087 ensureConnectionRelease();
1088 }
1089 }
1090
1091 /***
1092 * Remove the request header associated with the given name. Note that
1093 * header-name matching is case insensitive.
1094 *
1095 * @param headerName the header name
1096 */
1097 public void removeRequestHeader(String headerName) {
1098
1099 Header[] headers = getRequestHeaderGroup().getHeaders(headerName);
1100 for (int i = 0; i < headers.length; i++) {
1101 getRequestHeaderGroup().removeHeader(headers[i]);
1102 }
1103
1104 }
1105
1106 /***
1107 * Removes the given request header.
1108 *
1109 * @param header the header
1110 */
1111 public void removeRequestHeader(final Header header) {
1112 if (header == null) {
1113 return;
1114 }
1115 getRequestHeaderGroup().removeHeader(header);
1116 }
1117
1118
1119
1120 /***
1121 * Returns <tt>true</tt> the method is ready to execute, <tt>false</tt> otherwise.
1122 *
1123 * @return This implementation always returns <tt>true</tt>.
1124 */
1125 public boolean validate() {
1126 return true;
1127 }
1128
1129
1130 /***
1131 * Returns the actual cookie policy
1132 *
1133 * @param state HTTP state. TODO: to be removed in the future
1134 *
1135 * @return cookie spec
1136 */
1137 private CookieSpec getCookieSpec(final HttpState state) {
1138 if (this.cookiespec == null) {
1139 int i = state.getCookiePolicy();
1140 if (i == -1) {
1141 this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy());
1142 } else {
1143 this.cookiespec = CookiePolicy.getSpecByPolicy(i);
1144 }
1145 this.cookiespec.setValidDateFormats(
1146 (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS));
1147 }
1148 return this.cookiespec;
1149 }
1150
1151 /***
1152 * Generates <tt>Cookie</tt> request headers for those {@link Cookie cookie}s
1153 * that match the given host, port and path.
1154 *
1155 * @param state the {@link HttpState state} information associated with this method
1156 * @param conn the {@link HttpConnection connection} used to execute
1157 * this HTTP method
1158 *
1159 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1160 * can be recovered from.
1161 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1162 * cannot be recovered from.
1163 */
1164 protected void addCookieRequestHeader(HttpState state, HttpConnection conn)
1165 throws IOException, HttpException {
1166
1167 LOG.trace("enter HttpMethodBase.addCookieRequestHeader(HttpState, "
1168 + "HttpConnection)");
1169
1170 Header[] cookieheaders = getRequestHeaderGroup().getHeaders("Cookie");
1171 for (int i = 0; i < cookieheaders.length; i++) {
1172 Header cookieheader = cookieheaders[i];
1173 if (cookieheader.isAutogenerated()) {
1174 getRequestHeaderGroup().removeHeader(cookieheader);
1175 }
1176 }
1177
1178 CookieSpec matcher = getCookieSpec(state);
1179 Cookie[] cookies = matcher.match(conn.getHost(), conn.getPort(),
1180 getPath(), conn.isSecure(), state.getCookies());
1181 if ((cookies != null) && (cookies.length > 0)) {
1182 if (getParams().isParameterTrue(HttpMethodParams.SINGLE_COOKIE_HEADER)) {
1183
1184 String s = matcher.formatCookies(cookies);
1185 getRequestHeaderGroup().addHeader(new Header("Cookie", s, true));
1186 } else {
1187
1188 for (int i = 0; i < cookies.length; i++) {
1189 String s = matcher.formatCookie(cookies[i]);
1190 getRequestHeaderGroup().addHeader(new Header("Cookie", s, true));
1191 }
1192 }
1193 }
1194 }
1195
1196 /***
1197 * Generates <tt>Host</tt> request header, as long as no <tt>Host</tt> request
1198 * header already exists.
1199 *
1200 * @param state the {@link HttpState state} information associated with this method
1201 * @param conn the {@link HttpConnection connection} used to execute
1202 * this HTTP method
1203 *
1204 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1205 * can be recovered from.
1206 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1207 * cannot be recovered from.
1208 */
1209 protected void addHostRequestHeader(HttpState state, HttpConnection conn)
1210 throws IOException, HttpException {
1211 LOG.trace("enter HttpMethodBase.addHostRequestHeader(HttpState, "
1212 + "HttpConnection)");
1213
1214
1215
1216
1217
1218 String host = this.params.getVirtualHost();
1219 if (host != null) {
1220 LOG.debug("Using virtual host name: " + host);
1221 } else {
1222 host = conn.getHost();
1223 }
1224 int port = conn.getPort();
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234 if (LOG.isDebugEnabled()) {
1235 LOG.debug("Adding Host request header");
1236 }
1237
1238
1239 if (conn.getProtocol().getDefaultPort() != port) {
1240 host += (":" + port);
1241 }
1242
1243 setRequestHeader("Host", host);
1244 }
1245
1246 /***
1247 * Generates <tt>Proxy-Connection: Keep-Alive</tt> request header when
1248 * communicating via a proxy server.
1249 *
1250 * @param state the {@link HttpState state} information associated with this method
1251 * @param conn the {@link HttpConnection connection} used to execute
1252 * this HTTP method
1253 *
1254 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1255 * can be recovered from.
1256 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1257 * cannot be recovered from.
1258 */
1259 protected void addProxyConnectionHeader(HttpState state,
1260 HttpConnection conn)
1261 throws IOException, HttpException {
1262 LOG.trace("enter HttpMethodBase.addProxyConnectionHeader("
1263 + "HttpState, HttpConnection)");
1264 if (!conn.isTransparent()) {
1265 setRequestHeader("Proxy-Connection", "Keep-Alive");
1266 }
1267 }
1268
1269 /***
1270 * Generates all the required request {@link Header header}s
1271 * to be submitted via the given {@link HttpConnection connection}.
1272 *
1273 * <p>
1274 * This implementation adds <tt>User-Agent</tt>, <tt>Host</tt>,
1275 * <tt>Cookie</tt>, <tt>Authorization</tt>, <tt>Proxy-Authorization</tt>
1276 * and <tt>Proxy-Connection</tt> headers, when appropriate.
1277 * </p>
1278 *
1279 * <p>
1280 * Subclasses may want to override this method to to add additional
1281 * headers, and may choose to invoke this implementation (via
1282 * <tt>super</tt>) to add the "standard" headers.
1283 * </p>
1284 *
1285 * @param state the {@link HttpState state} information associated with this method
1286 * @param conn the {@link HttpConnection connection} used to execute
1287 * this HTTP method
1288 *
1289 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1290 * can be recovered from.
1291 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1292 * cannot be recovered from.
1293 *
1294 * @see #writeRequestHeaders
1295 */
1296 protected void addRequestHeaders(HttpState state, HttpConnection conn)
1297 throws IOException, HttpException {
1298 LOG.trace("enter HttpMethodBase.addRequestHeaders(HttpState, "
1299 + "HttpConnection)");
1300
1301 addUserAgentRequestHeader(state, conn);
1302 addHostRequestHeader(state, conn);
1303 addCookieRequestHeader(state, conn);
1304 addProxyConnectionHeader(state, conn);
1305 }
1306
1307 /***
1308 * Generates default <tt>User-Agent</tt> request header, as long as no
1309 * <tt>User-Agent</tt> request header already exists.
1310 *
1311 * @param state the {@link HttpState state} information associated with this method
1312 * @param conn the {@link HttpConnection connection} used to execute
1313 * this HTTP method
1314 *
1315 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1316 * can be recovered from.
1317 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1318 * cannot be recovered from.
1319 */
1320 protected void addUserAgentRequestHeader(HttpState state,
1321 HttpConnection conn)
1322 throws IOException, HttpException {
1323 LOG.trace("enter HttpMethodBase.addUserAgentRequestHeaders(HttpState, "
1324 + "HttpConnection)");
1325
1326 if (getRequestHeader("User-Agent") == null) {
1327 String agent = (String)getParams().getParameter(HttpMethodParams.USER_AGENT);
1328 if (agent == null) {
1329 agent = "Jakarta Commons-HttpClient";
1330 }
1331 setRequestHeader("User-Agent", agent);
1332 }
1333 }
1334
1335 /***
1336 * Throws an {@link IllegalStateException} if the HTTP method has been already
1337 * {@link #execute executed}, but not {@link #recycle recycled}.
1338 *
1339 * @throws IllegalStateException if the method has been used and not
1340 * recycled
1341 */
1342 protected void checkNotUsed() throws IllegalStateException {
1343 if (used) {
1344 throw new IllegalStateException("Already used.");
1345 }
1346 }
1347
1348 /***
1349 * Throws an {@link IllegalStateException} if the HTTP method has not been
1350 * {@link #execute executed} since last {@link #recycle recycle}.
1351 *
1352 *
1353 * @throws IllegalStateException if not used
1354 */
1355 protected void checkUsed() throws IllegalStateException {
1356 if (!used) {
1357 throw new IllegalStateException("Not Used.");
1358 }
1359 }
1360
1361
1362
1363 /***
1364 * Generates HTTP request line according to the specified attributes.
1365 *
1366 * @param connection the {@link HttpConnection connection} used to execute
1367 * this HTTP method
1368 * @param name the method name generate a request for
1369 * @param requestPath the path string for the request
1370 * @param query the query string for the request
1371 * @param version the protocol version to use (e.g. HTTP/1.0)
1372 *
1373 * @return HTTP request line
1374 */
1375 protected static String generateRequestLine(HttpConnection connection,
1376 String name, String requestPath, String query, String version) {
1377 LOG.trace("enter HttpMethodBase.generateRequestLine(HttpConnection, "
1378 + "String, String, String, String)");
1379
1380 StringBuffer buf = new StringBuffer();
1381
1382 buf.append(name);
1383 buf.append(" ");
1384
1385 if (!connection.isTransparent()) {
1386 Protocol protocol = connection.getProtocol();
1387 buf.append(protocol.getScheme().toLowerCase());
1388 buf.append("://");
1389 buf.append(connection.getHost());
1390 if ((connection.getPort() != -1)
1391 && (connection.getPort() != protocol.getDefaultPort())
1392 ) {
1393 buf.append(":");
1394 buf.append(connection.getPort());
1395 }
1396 }
1397
1398 if (requestPath == null) {
1399 buf.append("/");
1400 } else {
1401 if (!connection.isTransparent() && !requestPath.startsWith("/")) {
1402 buf.append("/");
1403 }
1404 buf.append(requestPath);
1405 }
1406
1407 if (query != null) {
1408 if (query.indexOf("?") != 0) {
1409 buf.append("?");
1410 }
1411 buf.append(query);
1412 }
1413
1414 buf.append(" ");
1415 buf.append(version);
1416 buf.append("\r\n");
1417
1418 return buf.toString();
1419 }
1420
1421 /***
1422 * This method is invoked immediately after
1423 * {@link #readResponseBody(HttpState,HttpConnection)} and can be overridden by
1424 * sub-classes in order to provide custom body processing.
1425 *
1426 * <p>
1427 * This implementation does nothing.
1428 * </p>
1429 *
1430 * @param state the {@link HttpState state} information associated with this method
1431 * @param conn the {@link HttpConnection connection} used to execute
1432 * this HTTP method
1433 *
1434 * @see #readResponse
1435 * @see #readResponseBody
1436 */
1437 protected void processResponseBody(HttpState state, HttpConnection conn) {
1438 }
1439
1440 /***
1441 * This method is invoked immediately after
1442 * {@link #readResponseHeaders(HttpState,HttpConnection)} and can be overridden by
1443 * sub-classes in order to provide custom response headers processing.
1444
1445 * <p>
1446 * This implementation will handle the <tt>Set-Cookie</tt> and
1447 * <tt>Set-Cookie2</tt> headers, if any, adding the relevant cookies to
1448 * the given {@link HttpState}.
1449 * </p>
1450 *
1451 * @param state the {@link HttpState state} information associated with this method
1452 * @param conn the {@link HttpConnection connection} used to execute
1453 * this HTTP method
1454 *
1455 * @see #readResponse
1456 * @see #readResponseHeaders
1457 */
1458 protected void processResponseHeaders(HttpState state,
1459 HttpConnection conn) {
1460 LOG.trace("enter HttpMethodBase.processResponseHeaders(HttpState, "
1461 + "HttpConnection)");
1462
1463 Header[] headers = getResponseHeaderGroup().getHeaders("set-cookie2");
1464
1465
1466 if (headers.length == 0) {
1467 headers = getResponseHeaderGroup().getHeaders("set-cookie");
1468 }
1469
1470 CookieSpec parser = getCookieSpec(state);
1471 for (int i = 0; i < headers.length; i++) {
1472 Header header = headers[i];
1473 Cookie[] cookies = null;
1474 try {
1475 cookies = parser.parse(
1476 conn.getHost(),
1477 conn.getPort(),
1478 getPath(),
1479 conn.isSecure(),
1480 header);
1481 } catch (MalformedCookieException e) {
1482 if (LOG.isWarnEnabled()) {
1483 LOG.warn("Invalid cookie header: \""
1484 + header.getValue()
1485 + "\". " + e.getMessage());
1486 }
1487 }
1488 if (cookies != null) {
1489 for (int j = 0; j < cookies.length; j++) {
1490 Cookie cookie = cookies[j];
1491 try {
1492 parser.validate(
1493 conn.getHost(),
1494 conn.getPort(),
1495 getPath(),
1496 conn.isSecure(),
1497 cookie);
1498 state.addCookie(cookie);
1499 if (LOG.isDebugEnabled()) {
1500 LOG.debug("Cookie accepted: \""
1501 + parser.formatCookie(cookie) + "\"");
1502 }
1503 } catch (MalformedCookieException e) {
1504 if (LOG.isWarnEnabled()) {
1505 LOG.warn("Cookie rejected: \"" + parser.formatCookie(cookie)
1506 + "\". " + e.getMessage());
1507 }
1508 }
1509 }
1510 }
1511 }
1512 }
1513
1514 /***
1515 * This method is invoked immediately after
1516 * {@link #readStatusLine(HttpState,HttpConnection)} and can be overridden by
1517 * sub-classes in order to provide custom response status line processing.
1518 *
1519 * @param state the {@link HttpState state} information associated with this method
1520 * @param conn the {@link HttpConnection connection} used to execute
1521 * this HTTP method
1522 *
1523 * @see #readResponse
1524 * @see #readStatusLine
1525 */
1526 protected void processStatusLine(HttpState state, HttpConnection conn) {
1527 }
1528
1529 /***
1530 * Reads the response from the given {@link HttpConnection connection}.
1531 *
1532 * <p>
1533 * The response is processed as the following sequence of actions:
1534 *
1535 * <ol>
1536 * <li>
1537 * {@link #readStatusLine(HttpState,HttpConnection)} is
1538 * invoked to read the request line.
1539 * </li>
1540 * <li>
1541 * {@link #processStatusLine(HttpState,HttpConnection)}
1542 * is invoked, allowing the method to process the status line if
1543 * desired.
1544 * </li>
1545 * <li>
1546 * {@link #readResponseHeaders(HttpState,HttpConnection)} is invoked to read
1547 * the associated headers.
1548 * </li>
1549 * <li>
1550 * {@link #processResponseHeaders(HttpState,HttpConnection)} is invoked, allowing
1551 * the method to process the headers if desired.
1552 * </li>
1553 * <li>
1554 * {@link #readResponseBody(HttpState,HttpConnection)} is
1555 * invoked to read the associated body (if any).
1556 * </li>
1557 * <li>
1558 * {@link #processResponseBody(HttpState,HttpConnection)} is invoked, allowing the
1559 * method to process the response body if desired.
1560 * </li>
1561 * </ol>
1562 *
1563 * Subclasses may want to override one or more of the above methods to to
1564 * customize the processing. (Or they may choose to override this method
1565 * if dramatically different processing is required.)
1566 * </p>
1567 *
1568 * @param state the {@link HttpState state} information associated with this method
1569 * @param conn the {@link HttpConnection connection} used to execute
1570 * this HTTP method
1571 *
1572 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1573 * can be recovered from.
1574 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1575 * cannot be recovered from.
1576 */
1577 protected void readResponse(HttpState state, HttpConnection conn)
1578 throws IOException, HttpException {
1579 LOG.trace(
1580 "enter HttpMethodBase.readResponse(HttpState, HttpConnection)");
1581
1582
1583 while (this.statusLine == null) {
1584 readStatusLine(state, conn);
1585 processStatusLine(state, conn);
1586 readResponseHeaders(state, conn);
1587 processResponseHeaders(state, conn);
1588
1589 int status = this.statusLine.getStatusCode();
1590 if ((status >= 100) && (status < 200)) {
1591 if (LOG.isInfoEnabled()) {
1592 LOG.info("Discarding unexpected response: " + this.statusLine.toString());
1593 }
1594 this.statusLine = null;
1595 }
1596 }
1597 readResponseBody(state, conn);
1598 processResponseBody(state, conn);
1599 }
1600
1601 /***
1602 * Read the response body from the given {@link HttpConnection}.
1603 *
1604 * <p>
1605 * The current implementation wraps the socket level stream with
1606 * an appropriate stream for the type of response (chunked, content-length,
1607 * or auto-close). If there is no response body, the connection associated
1608 * with the request will be returned to the connection manager.
1609 * </p>
1610 *
1611 * <p>
1612 * Subclasses may want to override this method to to customize the
1613 * processing.
1614 * </p>
1615 *
1616 * @param state the {@link HttpState state} information associated with this method
1617 * @param conn the {@link HttpConnection connection} used to execute
1618 * this HTTP method
1619 *
1620 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1621 * can be recovered from.
1622 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1623 * cannot be recovered from.
1624 *
1625 * @see #readResponse
1626 * @see #processResponseBody
1627 */
1628 protected void readResponseBody(HttpState state, HttpConnection conn)
1629 throws IOException, HttpException {
1630 LOG.trace(
1631 "enter HttpMethodBase.readResponseBody(HttpState, HttpConnection)");
1632
1633
1634 InputStream stream = readResponseBody(conn);
1635 if (stream == null) {
1636
1637 responseBodyConsumed();
1638 } else {
1639 conn.setLastResponseInputStream(stream);
1640 setResponseStream(stream);
1641 }
1642 }
1643
1644 /***
1645 * Returns the response body as an {@link InputStream input stream}
1646 * corresponding to the values of the <tt>Content-Length</tt> and
1647 * <tt>Transfer-Encoding</tt> headers. If no response body is available
1648 * returns <tt>null</tt>.
1649 * <p>
1650 *
1651 * @see #readResponse
1652 * @see #processResponseBody
1653 *
1654 * @param conn the {@link HttpConnection connection} used to execute
1655 * this HTTP method
1656 *
1657 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1658 * can be recovered from.
1659 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1660 * cannot be recovered from.
1661 */
1662 private InputStream readResponseBody(HttpConnection conn)
1663 throws HttpException, IOException {
1664
1665 LOG.trace("enter HttpMethodBase.readResponseBody(HttpConnection)");
1666
1667 responseBody = null;
1668 InputStream is = conn.getResponseInputStream();
1669 if (Wire.CONTENT_WIRE.enabled()) {
1670 is = new WireLogInputStream(is, Wire.CONTENT_WIRE);
1671 }
1672 InputStream result = null;
1673 Header transferEncodingHeader = responseHeaders.getFirstHeader("Transfer-Encoding");
1674
1675
1676 if (transferEncodingHeader != null) {
1677
1678 String transferEncoding = transferEncodingHeader.getValue();
1679 if (!"chunked".equalsIgnoreCase(transferEncoding)
1680 && !"identity".equalsIgnoreCase(transferEncoding)) {
1681 if (LOG.isWarnEnabled()) {
1682 LOG.warn("Unsupported transfer encoding: " + transferEncoding);
1683 }
1684 }
1685 HeaderElement[] encodings = transferEncodingHeader.getElements();
1686
1687
1688 int len = encodings.length;
1689 if ((len > 0) && ("chunked".equalsIgnoreCase(encodings[len - 1].getName()))) {
1690
1691 if (conn.isResponseAvailable(conn.getParams().getSoTimeout())) {
1692 result = new ChunkedInputStream(is, this);
1693 } else {
1694 if (getParams().isParameterTrue(HttpMethodParams.STRICT_TRANSFER_ENCODING)) {
1695 throw new ProtocolException("Chunk-encoded body declared but not sent");
1696 } else {
1697 LOG.warn("Chunk-encoded body missing");
1698 }
1699 }
1700 } else {
1701 LOG.info("Response content is not chunk-encoded");
1702
1703
1704 setConnectionCloseForced(true);
1705 result = is;
1706 }
1707 } else {
1708 long expectedLength = getResponseContentLength();
1709 if (expectedLength == -1) {
1710 Header connectionHeader = responseHeaders.getFirstHeader("Connection");
1711 String connectionDirective = null;
1712 if (connectionHeader != null) {
1713 connectionDirective = connectionHeader.getValue();
1714 }
1715 if (this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1) &&
1716 !"close".equalsIgnoreCase(connectionDirective)) {
1717 LOG.info("Response content length is not known");
1718 setConnectionCloseForced(true);
1719 }
1720 result = is;
1721 } else {
1722 result = new ContentLengthInputStream(is, expectedLength);
1723 }
1724 }
1725
1726
1727 if (!canResponseHaveBody(statusLine.getStatusCode())) {
1728 result = null;
1729 }
1730
1731
1732
1733 if (result != null) {
1734
1735 result = new AutoCloseInputStream(
1736 result,
1737 new ResponseConsumedWatcher() {
1738 public void responseConsumed() {
1739 responseBodyConsumed();
1740 }
1741 }
1742 );
1743 }
1744
1745 return result;
1746 }
1747
1748 /***
1749 * Reads the response headers from the given {@link HttpConnection connection}.
1750 *
1751 * <p>
1752 * Subclasses may want to override this method to to customize the
1753 * processing.
1754 * </p>
1755 *
1756 * <p>
1757 * "It must be possible to combine the multiple header fields into one
1758 * "field-name: field-value" pair, without changing the semantics of the
1759 * message, by appending each subsequent field-value to the first, each
1760 * separated by a comma." - HTTP/1.0 (4.3)
1761 * </p>
1762 *
1763 * @param state the {@link HttpState state} information associated with this method
1764 * @param conn the {@link HttpConnection connection} used to execute
1765 * this HTTP method
1766 *
1767 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1768 * can be recovered from.
1769 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1770 * cannot be recovered from.
1771 *
1772 * @see #readResponse
1773 * @see #processResponseHeaders
1774 */
1775 protected void readResponseHeaders(HttpState state, HttpConnection conn)
1776 throws IOException, HttpException {
1777 LOG.trace("enter HttpMethodBase.readResponseHeaders(HttpState,"
1778 + "HttpConnection)");
1779
1780 getResponseHeaderGroup().clear();
1781
1782 Header[] headers = HttpParser.parseHeaders(
1783 conn.getResponseInputStream(), getParams().getHttpElementCharset());
1784 if (Wire.HEADER_WIRE.enabled()) {
1785 for (int i = 0; i < headers.length; i++) {
1786 Wire.HEADER_WIRE.input(headers[i].toExternalForm());
1787 }
1788 }
1789 getResponseHeaderGroup().setHeaders(headers);
1790 }
1791
1792 /***
1793 * Read the status line from the given {@link HttpConnection}, setting my
1794 * {@link #getStatusCode status code} and {@link #getStatusText status
1795 * text}.
1796 *
1797 * <p>
1798 * Subclasses may want to override this method to to customize the
1799 * processing.
1800 * </p>
1801 *
1802 * @param state the {@link HttpState state} information associated with this method
1803 * @param conn the {@link HttpConnection connection} used to execute
1804 * this HTTP method
1805 *
1806 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1807 * can be recovered from.
1808 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1809 * cannot be recovered from.
1810 *
1811 * @see StatusLine
1812 */
1813 protected void readStatusLine(HttpState state, HttpConnection conn)
1814 throws IOException, HttpException {
1815 LOG.trace("enter HttpMethodBase.readStatusLine(HttpState, HttpConnection)");
1816
1817 final int maxGarbageLines = getParams().
1818 getIntParameter(HttpMethodParams.STATUS_LINE_GARBAGE_LIMIT, Integer.MAX_VALUE);
1819
1820
1821 int count = 0;
1822 String s;
1823 do {
1824 s = conn.readLine(getParams().getHttpElementCharset());
1825 if (s == null && count == 0) {
1826
1827 throw new NoHttpResponseException("The server " + conn.getHost() +
1828 " failed to respond");
1829 }
1830 if (Wire.HEADER_WIRE.enabled()) {
1831 Wire.HEADER_WIRE.input(s + "\r\n");
1832 }
1833 if (s != null && StatusLine.startsWithHTTP(s)) {
1834
1835 break;
1836 } else if (s == null || count >= maxGarbageLines) {
1837
1838 throw new ProtocolException("The server " + conn.getHost() +
1839 " failed to respond with a valid HTTP response");
1840 }
1841 count++;
1842 } while(true);
1843
1844
1845 statusLine = new StatusLine(s);
1846
1847
1848 String versionStr = statusLine.getHttpVersion();
1849 if (getParams().isParameterFalse(HttpMethodParams.UNAMBIGUOUS_STATUS_LINE)
1850 && versionStr.equals("HTTP")) {
1851 getParams().setVersion(HttpVersion.HTTP_1_0);
1852 if (LOG.isWarnEnabled()) {
1853 LOG.warn("Ambiguous status line (HTTP protocol version missing):" +
1854 statusLine.toString());
1855 }
1856 } else {
1857 this.effectiveVersion = HttpVersion.parse(versionStr);
1858 }
1859
1860 }
1861
1862
1863
1864 /***
1865 * <p>
1866 * Sends the request via the given {@link HttpConnection connection}.
1867 * </p>
1868 *
1869 * <p>
1870 * The request is written as the following sequence of actions:
1871 * </p>
1872 *
1873 * <ol>
1874 * <li>
1875 * {@link #writeRequestLine(HttpState, HttpConnection)} is invoked to
1876 * write the request line.
1877 * </li>
1878 * <li>
1879 * {@link #writeRequestHeaders(HttpState, HttpConnection)} is invoked
1880 * to write the associated headers.
1881 * </li>
1882 * <li>
1883 * <tt>\r\n</tt> is sent to close the head part of the request.
1884 * </li>
1885 * <li>
1886 * {@link #writeRequestBody(HttpState, HttpConnection)} is invoked to
1887 * write the body part of the request.
1888 * </li>
1889 * </ol>
1890 *
1891 * <p>
1892 * Subclasses may want to override one or more of the above methods to to
1893 * customize the processing. (Or they may choose to override this method
1894 * if dramatically different processing is required.)
1895 * </p>
1896 *
1897 * @param state the {@link HttpState state} information associated with this method
1898 * @param conn the {@link HttpConnection connection} used to execute
1899 * this HTTP method
1900 *
1901 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1902 * can be recovered from.
1903 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1904 * cannot be recovered from.
1905 */
1906 protected void writeRequest(HttpState state, HttpConnection conn)
1907 throws IOException, HttpException {
1908 LOG.trace(
1909 "enter HttpMethodBase.writeRequest(HttpState, HttpConnection)");
1910 writeRequestLine(state, conn);
1911 writeRequestHeaders(state, conn);
1912 conn.writeLine();
1913 if (Wire.HEADER_WIRE.enabled()) {
1914 Wire.HEADER_WIRE.output("\r\n");
1915 }
1916
1917 HttpVersion ver = getParams().getVersion();
1918 Header expectheader = getRequestHeader("Expect");
1919 String expectvalue = null;
1920 if (expectheader != null) {
1921 expectvalue = expectheader.getValue();
1922 }
1923 if ((expectvalue != null)
1924 && (expectvalue.compareToIgnoreCase("100-continue") == 0)) {
1925 if (ver.greaterEquals(HttpVersion.HTTP_1_1)) {
1926
1927
1928 conn.flushRequestOutputStream();
1929
1930 int readTimeout = conn.getParams().getSoTimeout();
1931 try {
1932 conn.setSocketTimeout(RESPONSE_WAIT_TIME_MS);
1933 readStatusLine(state, conn);
1934 processStatusLine(state, conn);
1935 readResponseHeaders(state, conn);
1936 processResponseHeaders(state, conn);
1937
1938 if (this.statusLine.getStatusCode() == HttpStatus.SC_CONTINUE) {
1939
1940 this.statusLine = null;
1941 LOG.debug("OK to continue received");
1942 } else {
1943 return;
1944 }
1945 } catch (InterruptedIOException e) {
1946 if (!ExceptionUtil.isSocketTimeoutException(e)) {
1947 throw e;
1948 }
1949
1950
1951
1952 removeRequestHeader("Expect");
1953 LOG.info("100 (continue) read timeout. Resume sending the request");
1954 } finally {
1955 conn.setSocketTimeout(readTimeout);
1956 }
1957
1958 } else {
1959 removeRequestHeader("Expect");
1960 LOG.info("'Expect: 100-continue' handshake is only supported by "
1961 + "HTTP/1.1 or higher");
1962 }
1963 }
1964
1965 writeRequestBody(state, conn);
1966
1967 conn.flushRequestOutputStream();
1968 }
1969
1970 /***
1971 * Writes the request body to the given {@link HttpConnection connection}.
1972 *
1973 * <p>
1974 * This method should return <tt>true</tt> if the request body was actually
1975 * sent (or is empty), or <tt>false</tt> if it could not be sent for some
1976 * reason.
1977 * </p>
1978 *
1979 * <p>
1980 * This implementation writes nothing and returns <tt>true</tt>.
1981 * </p>
1982 *
1983 * @param state the {@link HttpState state} information associated with this method
1984 * @param conn the {@link HttpConnection connection} used to execute
1985 * this HTTP method
1986 *
1987 * @return <tt>true</tt>
1988 *
1989 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
1990 * can be recovered from.
1991 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
1992 * cannot be recovered from.
1993 */
1994 protected boolean writeRequestBody(HttpState state, HttpConnection conn)
1995 throws IOException, HttpException {
1996 return true;
1997 }
1998
1999 /***
2000 * Writes the request headers to the given {@link HttpConnection connection}.
2001 *
2002 * <p>
2003 * This implementation invokes {@link #addRequestHeaders(HttpState,HttpConnection)},
2004 * and then writes each header to the request stream.
2005 * </p>
2006 *
2007 * <p>
2008 * Subclasses may want to override this method to to customize the
2009 * processing.
2010 * </p>
2011 *
2012 * @param state the {@link HttpState state} information associated with this method
2013 * @param conn the {@link HttpConnection connection} used to execute
2014 * this HTTP method
2015 *
2016 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
2017 * can be recovered from.
2018 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
2019 * cannot be recovered from.
2020 *
2021 * @see #addRequestHeaders
2022 * @see #getRequestHeaders
2023 */
2024 protected void writeRequestHeaders(HttpState state, HttpConnection conn)
2025 throws IOException, HttpException {
2026 LOG.trace("enter HttpMethodBase.writeRequestHeaders(HttpState,"
2027 + "HttpConnection)");
2028 addRequestHeaders(state, conn);
2029
2030 String charset = getParams().getHttpElementCharset();
2031
2032 Header[] headers = getRequestHeaders();
2033 for (int i = 0; i < headers.length; i++) {
2034 String s = headers[i].toExternalForm();
2035 if (Wire.HEADER_WIRE.enabled()) {
2036 Wire.HEADER_WIRE.output(s);
2037 }
2038 conn.print(s, charset);
2039 }
2040 }
2041
2042 /***
2043 * Writes the request line to the given {@link HttpConnection connection}.
2044 *
2045 * <p>
2046 * Subclasses may want to override this method to to customize the
2047 * processing.
2048 * </p>
2049 *
2050 * @param state the {@link HttpState state} information associated with this method
2051 * @param conn the {@link HttpConnection connection} used to execute
2052 * this HTTP method
2053 *
2054 * @throws IOException if an I/O (transport) error occurs. Some transport exceptions
2055 * can be recovered from.
2056 * @throws HttpException if a protocol exception occurs. Usually protocol exceptions
2057 * cannot be recovered from.
2058 *
2059 * @see #generateRequestLine
2060 */
2061 protected void writeRequestLine(HttpState state, HttpConnection conn)
2062 throws IOException, HttpException {
2063 LOG.trace(
2064 "enter HttpMethodBase.writeRequestLine(HttpState, HttpConnection)");
2065 String requestLine = getRequestLine(conn);
2066 if (Wire.HEADER_WIRE.enabled()) {
2067 Wire.HEADER_WIRE.output(requestLine);
2068 }
2069 conn.print(requestLine, getParams().getHttpElementCharset());
2070 }
2071
2072 /***
2073 * Returns the request line.
2074 *
2075 * @param conn the {@link HttpConnection connection} used to execute
2076 * this HTTP method
2077 *
2078 * @return The request line.
2079 */
2080 private String getRequestLine(HttpConnection conn) {
2081 return HttpMethodBase.generateRequestLine(conn, getName(),
2082 getPath(), getQueryString(), this.effectiveVersion.toString());
2083 }
2084
2085 /***
2086 * Returns {@link HttpMethodParams HTTP protocol parameters} associated with this method.
2087 *
2088 * @return HTTP parameters.
2089 *
2090 * @since 3.0
2091 */
2092 public HttpMethodParams getParams() {
2093 return this.params;
2094 }
2095
2096 /***
2097 * Assigns {@link HttpMethodParams HTTP protocol parameters} for this method.
2098 *
2099 * @since 3.0
2100 *
2101 * @see HttpMethodParams
2102 */
2103 public void setParams(final HttpMethodParams params) {
2104 if (params == null) {
2105 throw new IllegalArgumentException("Parameters may not be null");
2106 }
2107 this.params = params;
2108 }
2109
2110 /***
2111 * Returns the HTTP version used with this method (may be <tt>null</tt>
2112 * if undefined, that is, the method has not been executed)
2113 *
2114 * @return HTTP version.
2115 *
2116 * @since 3.0
2117 */
2118 public HttpVersion getEffectiveVersion() {
2119 return this.effectiveVersion;
2120 }
2121
2122 /***
2123 * Per RFC 2616 section 4.3, some response can never contain a message
2124 * body.
2125 *
2126 * @param status - the HTTP status code
2127 *
2128 * @return <tt>true</tt> if the message may contain a body, <tt>false</tt> if it can not
2129 * contain a message body
2130 */
2131 private static boolean canResponseHaveBody(int status) {
2132 LOG.trace("enter HttpMethodBase.canResponseHaveBody(int)");
2133
2134 boolean result = true;
2135
2136 if ((status >= 100 && status <= 199) || (status == 204)
2137 || (status == 304)) {
2138 result = false;
2139 }
2140
2141 return result;
2142 }
2143
2144 /***
2145 * Returns proxy authentication realm, if it has been used during authentication process.
2146 * Otherwise returns <tt>null</tt>.
2147 *
2148 * @return proxy authentication realm
2149 *
2150 * @deprecated use #getProxyAuthState()
2151 */
2152 public String getProxyAuthenticationRealm() {
2153 return this.proxyAuthState.getRealm();
2154 }
2155
2156 /***
2157 * Returns authentication realm, if it has been used during authentication process.
2158 * Otherwise returns <tt>null</tt>.
2159 *
2160 * @return authentication realm
2161 *
2162 * @deprecated use #getHostAuthState()
2163 */
2164 public String getAuthenticationRealm() {
2165 return this.hostAuthState.getRealm();
2166 }
2167
2168 /***
2169 * Returns the character set from the <tt>Content-Type</tt> header.
2170 *
2171 * @param contentheader The content header.
2172 * @return String The character set.
2173 */
2174 protected String getContentCharSet(Header contentheader) {
2175 LOG.trace("enter getContentCharSet( Header contentheader )");
2176 String charset = null;
2177 if (contentheader != null) {
2178 HeaderElement values[] = contentheader.getElements();
2179
2180
2181 if (values.length == 1) {
2182 NameValuePair param = values[0].getParameterByName("charset");
2183 if (param != null) {
2184
2185
2186 charset = param.getValue();
2187 }
2188 }
2189 }
2190 if (charset == null) {
2191 charset = getParams().getContentCharset();
2192 if (LOG.isDebugEnabled()) {
2193 LOG.debug("Default charset used: " + charset);
2194 }
2195 }
2196 return charset;
2197 }
2198
2199
2200 /***
2201 * Returns the character encoding of the request from the <tt>Content-Type</tt> header.
2202 *
2203 * @return String The character set.
2204 */
2205 public String getRequestCharSet() {
2206 return getContentCharSet(getRequestHeader("Content-Type"));
2207 }
2208
2209
2210 /***
2211 * Returns the character encoding of the response from the <tt>Content-Type</tt> header.
2212 *
2213 * @return String The character set.
2214 */
2215 public String getResponseCharSet() {
2216 return getContentCharSet(getResponseHeader("Content-Type"));
2217 }
2218
2219 /***
2220 * @deprecated no longer used
2221 *
2222 * Returns the number of "recoverable" exceptions thrown and handled, to
2223 * allow for monitoring the quality of the connection.
2224 *
2225 * @return The number of recoverable exceptions handled by the method.
2226 */
2227 public int getRecoverableExceptionCount() {
2228 return recoverableExceptionCount;
2229 }
2230
2231 /***
2232 * A response has been consumed.
2233 *
2234 * <p>The default behavior for this class is to check to see if the connection
2235 * should be closed, and close if need be, and to ensure that the connection
2236 * is returned to the connection manager - if and only if we are not still
2237 * inside the execute call.</p>
2238 *
2239 */
2240 protected void responseBodyConsumed() {
2241
2242
2243
2244 responseStream = null;
2245 if (responseConnection != null) {
2246 responseConnection.setLastResponseInputStream(null);
2247
2248
2249
2250
2251
2252 if (shouldCloseConnection(responseConnection)) {
2253 responseConnection.close();
2254 } else {
2255 try {
2256 if(responseConnection.isResponseAvailable()) {
2257 boolean logExtraInput =
2258 getParams().isParameterTrue(HttpMethodParams.WARN_EXTRA_INPUT);
2259
2260 if(logExtraInput) {
2261 LOG.warn("Extra response data detected - closing connection");
2262 }
2263 responseConnection.close();
2264 }
2265 }
2266 catch (IOException e) {
2267 LOG.warn(e.getMessage());
2268 responseConnection.close();
2269 }
2270 }
2271 }
2272 this.connectionCloseForced = false;
2273 ensureConnectionRelease();
2274 }
2275
2276 /***
2277 * Insure that the connection is released back to the pool.
2278 */
2279 private void ensureConnectionRelease() {
2280 if (responseConnection != null) {
2281 responseConnection.releaseConnection();
2282 responseConnection = null;
2283 }
2284 }
2285
2286 /***
2287 * Returns the {@link HostConfiguration host configuration}.
2288 *
2289 * @return the host configuration
2290 *
2291 * @deprecated no longer applicable
2292 */
2293 public HostConfiguration getHostConfiguration() {
2294 HostConfiguration hostconfig = new HostConfiguration();
2295 hostconfig.setHost(this.httphost);
2296 return hostconfig;
2297 }
2298 /***
2299 * Sets the {@link HostConfiguration host configuration}.
2300 *
2301 * @param hostconfig The hostConfiguration to set
2302 *
2303 * @deprecated no longer applicable
2304 */
2305 public void setHostConfiguration(final HostConfiguration hostconfig) {
2306 if (hostconfig != null) {
2307 this.httphost = new HttpHost(
2308 hostconfig.getHost(),
2309 hostconfig.getPort(),
2310 hostconfig.getProtocol());
2311 } else {
2312 this.httphost = null;
2313 }
2314 }
2315
2316 /***
2317 * Returns the {@link MethodRetryHandler retry handler} for this HTTP method
2318 *
2319 * @return the methodRetryHandler
2320 *
2321 * @deprecated use {@link HttpMethodParams}
2322 */
2323 public MethodRetryHandler getMethodRetryHandler() {
2324 return methodRetryHandler;
2325 }
2326
2327 /***
2328 * Sets the {@link MethodRetryHandler retry handler} for this HTTP method
2329 *
2330 * @param handler the methodRetryHandler to use when this method executed
2331 *
2332 * @deprecated use {@link HttpMethodParams}
2333 */
2334 public void setMethodRetryHandler(MethodRetryHandler handler) {
2335 methodRetryHandler = handler;
2336 }
2337
2338 /***
2339 * This method is a dirty hack intended to work around
2340 * current (2.0) design flaw that prevents the user from
2341 * obtaining correct status code, headers and response body from the
2342 * preceding HTTP CONNECT method.
2343 *
2344 * TODO: Remove this crap as soon as possible
2345 */
2346 void fakeResponse(
2347 StatusLine statusline,
2348 HeaderGroup responseheaders,
2349 InputStream responseStream
2350 ) {
2351
2352 this.used = true;
2353 this.statusLine = statusline;
2354 this.responseHeaders = responseheaders;
2355 this.responseBody = null;
2356 this.responseStream = responseStream;
2357 }
2358
2359 /***
2360 * Returns the target host {@link AuthState authentication state}
2361 *
2362 * @return host authentication state
2363 *
2364 * @since 3.0
2365 */
2366 public AuthState getHostAuthState() {
2367 return this.hostAuthState;
2368 }
2369
2370 /***
2371 * Returns the proxy {@link AuthState authentication state}
2372 *
2373 * @return host authentication state
2374 *
2375 * @since 3.0
2376 */
2377 public AuthState getProxyAuthState() {
2378 return this.proxyAuthState;
2379 }
2380
2381 /***
2382 * Tests whether the execution of this method has been aborted
2383 *
2384 * @return <tt>true</tt> if the execution of this method has been aborted,
2385 * <tt>false</tt> otherwise
2386 *
2387 * @since 3.0
2388 */
2389 public boolean isAborted() {
2390 return this.aborted;
2391 }
2392
2393 /***
2394 * Returns <tt>true</tt> if the HTTP has been transmitted to the target
2395 * server in its entirety, <tt>false</tt> otherwise. This flag can be useful
2396 * for recovery logic. If the request has not been transmitted in its entirety,
2397 * it is safe to retry the failed method.
2398 *
2399 * @return <tt>true</tt> if the request has been sent, <tt>false</tt> otherwise
2400 */
2401 public boolean isRequestSent() {
2402 return this.requestSent;
2403 }
2404
2405 }