/
HttpMethodBase.java
2423 lines (2217 loc) · 85 KB
/
HttpMethodBase.java
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* $Header: /home/jerenkrantz/tmp/commons/commons-convert/cvs/home/cvs/jakarta-commons//httpclient/src/java/org/apache/commons/httpclient/HttpMethodBase.java,v 1.222 2005/01/14 21:16:40 olegk Exp $
* $Revision$
* $Date$
*
* ====================================================================
*
* Copyright 1999-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.commons.httpclient;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.util.Collection;
import org.apache.commons.httpclient.auth.AuthState;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.cookie.MalformedCookieException;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.util.EncodingUtil;
import org.apache.commons.httpclient.util.ExceptionUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* An abstract base implementation of HttpMethod.
* <p>
* At minimum, subclasses will need to override:
* <ul>
* <li>{@link #getName} to return the approriate name for this method
* </li>
* </ul>
* </p>
*
* <p>
* When a method requires additional request headers, subclasses will typically
* want to override:
* <ul>
* <li>{@link #addRequestHeaders addRequestHeaders(HttpState,HttpConnection)}
* to write those headers
* </li>
* </ul>
* </p>
*
* <p>
* When a method expects specific response headers, subclasses may want to
* override:
* <ul>
* <li>{@link #processResponseHeaders processResponseHeaders(HttpState,HttpConnection)}
* to handle those headers
* </li>
* </ul>
* </p>
*
*
* @author <a href="mailto:remm@apache.org">Remy Maucherat</a>
* @author Rodney Waldhoff
* @author Sean C. Sullivan
* @author <a href="mailto:dion@apache.org">dIon Gillard</a>
* @author <a href="mailto:jsdever@apache.org">Jeff Dever</a>
* @author <a href="mailto:dims@apache.org">Davanum Srinivas</a>
* @author Ortwin Glueck
* @author Eric Johnson
* @author Michael Becke
* @author <a href="mailto:oleg@ural.ru">Oleg Kalnichevski</a>
* @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @author Christian Kohlschuetter
*
* @version $Revision$ $Date$
*/
@SuppressWarnings({"deprecation"}) // <- // IA/HERITRIX change
public abstract class HttpMethodBase implements HttpMethod {
// -------------------------------------------------------------- Constants
/** Log object for this class. */
private static final Log LOG = LogFactory.getLog(HttpMethodBase.class);
// ----------------------------------------------------- Instance variables
/** Request headers, if any. */
private HeaderGroup requestHeaders = new HeaderGroup();
/** The Status-Line from the response. */
private StatusLine statusLine = null;
/** Response headers, if any. */
private HeaderGroup responseHeaders = new HeaderGroup();
/** Response trailer headers, if any. */
private HeaderGroup responseTrailerHeaders = new HeaderGroup();
/** Path of the HTTP method. */
private String path = null;
/** Query string of the HTTP method, if any. */
private String queryString = null;
/** The response body of the HTTP method, assuming it has not be
* intercepted by a sub-class. */
private InputStream responseStream = null;
/** The connection that the response stream was read from. */
private HttpConnection responseConnection = null;
/** Buffer for the response */
private byte[] responseBody = null;
/** True if the HTTP method should automatically follow HTTP redirects.*/
private boolean followRedirects = false;
/** True if the HTTP method should automatically handle
* HTTP authentication challenges. */
private boolean doAuthentication = true;
/** HTTP protocol parameters. */
private HttpMethodParams params = new HttpMethodParams();
/** Host authentication state */
private AuthState hostAuthState = new AuthState();
/** Proxy authentication state */
private AuthState proxyAuthState = new AuthState();
/** True if this method has already been executed. */
private boolean used = false;
/** Count of how many times did this HTTP method transparently handle
* a recoverable exception. */
private int recoverableExceptionCount = 0;
/** the host for this HTTP method, can be null */
private HttpHost httphost = null;
/**
* Handles method retries
*
* @deprecated no loner used
*/
private MethodRetryHandler methodRetryHandler;
/** True if the connection must be closed when no longer needed */
private boolean connectionCloseForced = false;
/** Number of milliseconds to wait for 100-contunue response. */
private static final int RESPONSE_WAIT_TIME_MS = 3000;
/** HTTP protocol version used for execution of this method. */
private HttpVersion effectiveVersion = null;
/** Whether the execution of this method has been aborted */
private transient boolean aborted = false;
/** Whether the HTTP request has been transmitted to the target
* server it its entirety */
private boolean requestSent = false;
/** Actual cookie policy */
private CookieSpec cookiespec = null;
/** Default initial size of the response buffer if content length is unknown. */
private static final int DEFAULT_INITIAL_BUFFER_SIZE = 4*1024; // 4 kB
// ----------------------------------------------------------- Constructors
/**
* No-arg constructor.
*/
public HttpMethodBase() {
}
/**
* Constructor specifying a URI.
* It is responsibility of the caller to ensure that URI elements
* (path & query parameters) are properly encoded (URL safe).
*
* @param uri either an absolute or relative URI. The URI is expected
* to be URL-encoded
*
* @throws IllegalArgumentException when URI is invalid
* @throws IllegalStateException when protocol of the absolute URI is not recognised
*/
public HttpMethodBase(String uri)
throws IllegalArgumentException, IllegalStateException {
try {
// create a URI and allow for null/empty uri values
if (uri == null || uri.equals("")) {
uri = "/";
}
// BEGIN IA/HERITRIX CHANGES
// setURI(new URI(uri, true));
setURI(new org.archive.net.LaxURI(uri, true));
// END IA/HERITRIX CHANGES
} catch (URIException e) {
throw new IllegalArgumentException("Invalid uri '"
+ uri + "': " + e.getMessage()
);
}
}
// ------------------------------------------- Property Setters and Getters
/**
* Obtains the name of the HTTP method as used in the HTTP request line,
* for example <tt>"GET"</tt> or <tt>"POST"</tt>.
*
* @return the name of this method
*/
public abstract String getName();
/**
* Returns the URI of the HTTP method
*
* @return The URI
*
* @throws URIException If the URI cannot be created.
*
* @see org.apache.commons.httpclient.HttpMethod#getURI()
*/
public URI getURI() throws URIException {
StringBuffer buffer = new StringBuffer();
if (this.httphost != null) {
buffer.append(this.httphost.getProtocol().getScheme());
buffer.append("://");
buffer.append(this.httphost.getHostName());
int port = this.httphost.getPort();
if (port != -1 && port != this.httphost.getProtocol().getDefaultPort()) {
buffer.append(":");
buffer.append(port);
}
}
buffer.append(this.path);
if (this.queryString != null) {
buffer.append('?');
buffer.append(this.queryString);
}
// BEGIN IA/HERITRIX CHANGES
// return new URI(buffer.toString(), true);
return new org.archive.net.LaxURI(buffer.toString(), true);
// END IA/HERITRIX CHANGES
}
/**
* Sets the URI for this method.
*
* @param uri URI to be set
*
* @throws URIException if a URI cannot be set
*
* @since 3.0
*/
public void setURI(URI uri) throws URIException {
// only set the host if specified by the URI
if (uri.isAbsoluteURI()) {
this.httphost = new HttpHost(uri);
}
// set the path, defaulting to root
setPath(
uri.getPath() == null
? "/"
: uri.getEscapedPath()
);
setQueryString(uri.getEscapedQuery());
}
/**
* Sets whether or not the HTTP method should automatically follow HTTP redirects
* (status code 302, etc.)
*
* @param followRedirects <tt>true</tt> if the method will automatically follow redirects,
* <tt>false</tt> otherwise.
*/
public void setFollowRedirects(boolean followRedirects) {
this.followRedirects = followRedirects;
}
/**
* Returns <tt>true</tt> if the HTTP method should automatically follow HTTP redirects
* (status code 302, etc.), <tt>false</tt> otherwise.
*
* @return <tt>true</tt> if the method will automatically follow HTTP redirects,
* <tt>false</tt> otherwise.
*/
public boolean getFollowRedirects() {
return this.followRedirects;
}
/** Sets whether version 1.1 of the HTTP protocol should be used per default.
*
* @param http11 <tt>true</tt> to use HTTP/1.1, <tt>false</tt> to use 1.0
*
* @deprecated Use {@link HttpMethodParams#setVersion(HttpVersion)}
*/
public void setHttp11(boolean http11) {
if (http11) {
this.params.setVersion(HttpVersion.HTTP_1_1);
} else {
this.params.setVersion(HttpVersion.HTTP_1_0);
}
}
/**
* Returns <tt>true</tt> if the HTTP method should automatically handle HTTP
* authentication challenges (status code 401, etc.), <tt>false</tt> otherwise
*
* @return <tt>true</tt> if authentication challenges will be processed
* automatically, <tt>false</tt> otherwise.
*
* @since 2.0
*/
public boolean getDoAuthentication() {
return doAuthentication;
}
/**
* Sets whether or not the HTTP method should automatically handle HTTP
* authentication challenges (status code 401, etc.)
*
* @param doAuthentication <tt>true</tt> to process authentication challenges
* authomatically, <tt>false</tt> otherwise.
*
* @since 2.0
*/
public void setDoAuthentication(boolean doAuthentication) {
this.doAuthentication = doAuthentication;
}
// ---------------------------------------------- Protected Utility Methods
/**
* Returns <tt>true</tt> if version 1.1 of the HTTP protocol should be
* used per default, <tt>false</tt> if version 1.0 should be used.
*
* @return <tt>true</tt> to use HTTP/1.1, <tt>false</tt> to use 1.0
*
* @deprecated Use {@link HttpMethodParams#getVersion()}
*/
public boolean isHttp11() {
return this.params.getVersion().equals(HttpVersion.HTTP_1_1);
}
/**
* Sets the path of the HTTP method.
* It is responsibility of the caller to ensure that the path is
* properly encoded (URL safe).
*
* @param path the path of the HTTP method. The path is expected
* to be URL-encoded
*/
public void setPath(String path) {
this.path = path;
}
/**
* Adds the specified request header, NOT overwriting any previous value.
* Note that header-name matching is case insensitive.
*
* @param header the header to add to the request
*/
public void addRequestHeader(Header header) {
LOG.trace("HttpMethodBase.addRequestHeader(Header)");
if (header == null) {
LOG.debug("null header value ignored");
} else {
getRequestHeaderGroup().addHeader(header);
}
}
/**
* Use this method internally to add footers.
*
* @param footer The footer to add.
*/
public void addResponseFooter(Header footer) {
getResponseTrailerHeaderGroup().addHeader(footer);
}
/**
* Gets the path of this HTTP method.
* Calling this method <em>after</em> the request has been executed will
* return the <em>actual</em> path, following any redirects automatically
* handled by this HTTP method.
*
* @return the path to request or "/" if the path is blank.
*/
public String getPath() {
return (path == null || path.equals("")) ? "/" : path;
}
/**
* Sets the query string of this HTTP method. The caller must ensure that the string
* is properly URL encoded. The query string should not start with the question
* mark character.
*
* @param queryString the query string
*
* @see EncodingUtil#formUrlEncode(NameValuePair[], String)
*/
public void setQueryString(String queryString) {
this.queryString = queryString;
}
/**
* Sets the query string of this HTTP method. The pairs are encoded as UTF-8 characters.
* To use a different charset the parameters can be encoded manually using EncodingUtil
* and set as a single String.
*
* @param params an array of {@link NameValuePair}s to add as query string
* parameters. The name/value pairs will be automcatically
* URL encoded
*
* @see EncodingUtil#formUrlEncode(NameValuePair[], String)
* @see #setQueryString(String)
*/
public void setQueryString(NameValuePair[] params) {
LOG.trace("enter HttpMethodBase.setQueryString(NameValuePair[])");
queryString = EncodingUtil.formUrlEncode(params, "UTF-8");
}
/**
* Gets the query string of this HTTP method.
*
* @return The query string
*/
public String getQueryString() {
return queryString;
}
/**
* Set the specified request header, overwriting any previous value. Note
* that header-name matching is case-insensitive.
*
* @param headerName the header's name
* @param headerValue the header's value
*/
public void setRequestHeader(String headerName, String headerValue) {
Header header = new Header(headerName, headerValue);
setRequestHeader(header);
}
/**
* Sets the specified request header, overwriting any previous value.
* Note that header-name matching is case insensitive.
*
* @param header the header
*/
public void setRequestHeader(Header header) {
Header[] headers = getRequestHeaderGroup().getHeaders(header.getName());
for (int i = 0; i < headers.length; i++) {
getRequestHeaderGroup().removeHeader(headers[i]);
}
getRequestHeaderGroup().addHeader(header);
}
/**
* Returns the specified request header. Note that header-name matching is
* case insensitive. <tt>null</tt> will be returned if either
* <i>headerName</i> is <tt>null</tt> or there is no matching header for
* <i>headerName</i>.
*
* @param headerName The name of the header to be returned.
*
* @return The specified request header.
*
* @since 3.0
*/
public Header getRequestHeader(String headerName) {
if (headerName == null) {
return null;
} else {
return getRequestHeaderGroup().getCondensedHeader(headerName);
}
}
/**
* Returns an array of the requests headers that the HTTP method currently has
*
* @return an array of my request headers.
*/
public Header[] getRequestHeaders() {
return getRequestHeaderGroup().getAllHeaders();
}
/**
* @see org.apache.commons.httpclient.HttpMethod#getRequestHeaders(java.lang.String)
*/
public Header[] getRequestHeaders(String headerName) {
return getRequestHeaderGroup().getHeaders(headerName);
}
/**
* Gets the {@link HeaderGroup header group} storing the request headers.
*
* @return a HeaderGroup
*
* @since 2.0beta1
*/
protected HeaderGroup getRequestHeaderGroup() {
return requestHeaders;
}
/**
* Gets the {@link HeaderGroup header group} storing the response trailer headers
* as per RFC 2616 section 3.6.1.
*
* @return a HeaderGroup
*
* @since 2.0beta1
*/
protected HeaderGroup getResponseTrailerHeaderGroup() {
return responseTrailerHeaders;
}
/**
* Gets the {@link HeaderGroup header group} storing the response headers.
*
* @return a HeaderGroup
*
* @since 2.0beta1
*/
protected HeaderGroup getResponseHeaderGroup() {
return responseHeaders;
}
/**
* @see org.apache.commons.httpclient.HttpMethod#getResponseHeaders(java.lang.String)
*
* @since 3.0
*/
public Header[] getResponseHeaders(String headerName) {
return getResponseHeaderGroup().getHeaders(headerName);
}
/**
* Returns the response status code.
*
* @return the status code associated with the latest response.
*/
public int getStatusCode() {
return statusLine.getStatusCode();
}
/**
* Provides access to the response status line.
*
* @return the status line object from the latest response.
* @since 2.0
*/
public StatusLine getStatusLine() {
return statusLine;
}
/**
* Checks if response data is available.
* @return <tt>true</tt> if response data is available, <tt>false</tt> otherwise.
*/
private boolean responseAvailable() {
return (responseBody != null) || (responseStream != null);
}
/**
* Returns an array of the response headers that the HTTP method currently has
* in the order in which they were read.
*
* @return an array of response headers.
*/
public Header[] getResponseHeaders() {
return getResponseHeaderGroup().getAllHeaders();
}
/**
* Gets the response header associated with the given name. Header name
* matching is case insensitive. <tt>null</tt> will be returned if either
* <i>headerName</i> is <tt>null</tt> or there is no matching header for
* <i>headerName</i>.
*
* @param headerName the header name to match
*
* @return the matching header
*/
public Header getResponseHeader(String headerName) {
if (headerName == null) {
return null;
} else {
return getResponseHeaderGroup().getCondensedHeader(headerName);
}
}
/**
* Return the length (in bytes) of the response body, as specified in a
* <tt>Content-Length</tt> header.
*
* <p>
* Return <tt>-1</tt> when the content-length is unknown.
* </p>
*
* @return content length, if <tt>Content-Length</tt> header is available.
* <tt>0</tt> indicates that the request has no body.
* If <tt>Content-Length</tt> header is not present, the method
* returns <tt>-1</tt>.
*/
public long getResponseContentLength() {
Header[] headers = getResponseHeaderGroup().getHeaders("Content-Length");
if (headers.length == 0) {
return -1;
}
if (headers.length > 1) {
LOG.warn("Multiple content-length headers detected");
}
for (int i = headers.length - 1; i >= 0; i--) {
Header header = headers[i];
try {
return Long.parseLong(header.getValue());
} catch (NumberFormatException e) {
if (LOG.isWarnEnabled()) {
LOG.warn("Invalid content-length value: " + e.getMessage());
}
}
// See if we can have better luck with another header, if present
}
return -1;
}
/**
* Returns the response body of the HTTP method, if any, as an array of bytes.
* If response body is not available or cannot be read, returns <tt>null</tt>
*
* Note: This will cause the entire response body to be buffered in memory. A
* malicious server may easily exhaust all the VM memory. It is strongly
* recommended, to use getResponseAsStream if the content length of the response
* is unknown or resonably large.
*
* @return The response body.
*
* @throws IOException If an I/O (transport) problem occurs while obtaining the
* response body.
*/
public byte[] getResponseBody() throws IOException {
if (this.responseBody == null) {
InputStream instream = getResponseBodyAsStream();
if (instream != null) {
long contentLength = getResponseContentLength();
if (contentLength > Integer.MAX_VALUE) { //guard below cast from overflow
throw new IOException("Content too large to be buffered: "+ contentLength +" bytes");
}
int limit = getParams().getIntParameter(HttpMethodParams.BUFFER_WARN_TRIGGER_LIMIT, 1024*1024);
if ((contentLength == -1) || (contentLength > limit)) {
LOG.warn("Going to buffer response body of large or unknown size. "
+"Using getResponseBodyAsStream instead is recommended.");
}
LOG.debug("Buffering response body");
ByteArrayOutputStream outstream = new ByteArrayOutputStream(
contentLength > 0 ? (int) contentLength : DEFAULT_INITIAL_BUFFER_SIZE);
byte[] buffer = new byte[4096];
int len;
while ((len = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, len);
}
outstream.close();
setResponseStream(null);
this.responseBody = outstream.toByteArray();
}
}
return this.responseBody;
}
/**
* Returns the response body of the HTTP method, if any, as an {@link InputStream}.
* If response body is not available, returns <tt>null</tt>
*
* @return The response body
*
* @throws IOException If an I/O (transport) problem occurs while obtaining the
* response body.
*/
public InputStream getResponseBodyAsStream() throws IOException {
if (responseStream != null) {
return responseStream;
}
if (responseBody != null) {
InputStream byteResponseStream = new ByteArrayInputStream(responseBody);
LOG.debug("re-creating response stream from byte array");
return byteResponseStream;
}
return null;
}
/**
* Returns the response body of the HTTP method, if any, as a {@link String}.
* If response body is not available or cannot be read, returns <tt>null</tt>
* The string conversion on the data is done using the character encoding specified
* in <tt>Content-Type</tt> header.
*
* Note: This will cause the entire response body to be buffered in memory. A
* malicious server may easily exhaust all the VM memory. It is strongly
* recommended, to use getResponseAsStream if the content length of the response
* is unknown or resonably large.
*
* @return The response body.
*
* @throws IOException If an I/O (transport) problem occurs while obtaining the
* response body.
*/
public String getResponseBodyAsString() throws IOException {
byte[] rawdata = null;
if (responseAvailable()) {
rawdata = getResponseBody();
}
if (rawdata != null) {
return EncodingUtil.getString(rawdata, getResponseCharSet());
} else {
return null;
}
}
/**
* Returns an array of the response footers that the HTTP method currently has
* in the order in which they were read.
*
* @return an array of footers
*/
public Header[] getResponseFooters() {
return getResponseTrailerHeaderGroup().getAllHeaders();
}
/**
* Gets the response footer associated with the given name.
* Footer name matching is case insensitive.
* <tt>null</tt> will be returned if either <i>footerName</i> is
* <tt>null</tt> or there is no matching footer for <i>footerName</i>
* or there are no footers available. If there are multiple footers
* with the same name, there values will be combined with the ',' separator
* as specified by RFC2616.
*
* @param footerName the footer name to match
* @return the matching footer
*/
public Header getResponseFooter(String footerName) {
if (footerName == null) {
return null;
} else {
return getResponseTrailerHeaderGroup().getCondensedHeader(footerName);
}
}
/**
* Sets the response stream.
* @param responseStream The new response stream.
*/
protected void setResponseStream(InputStream responseStream) {
this.responseStream = responseStream;
}
/**
* Returns a stream from which the body of the current response may be read.
* If the method has not yet been executed, if <code>responseBodyConsumed</code>
* has been called, or if the stream returned by a previous call has been closed,
* <code>null</code> will be returned.
*
* @return the current response stream
*/
protected InputStream getResponseStream() {
return responseStream;
}
/**
* Returns the status text (or "reason phrase") associated with the latest
* response.
*
* @return The status text.
*/
public String getStatusText() {
return statusLine.getReasonPhrase();
}
/**
* Defines how strictly HttpClient follows the HTTP protocol specification
* (RFC 2616 and other relevant RFCs). In the strict mode HttpClient precisely
* implements the requirements of the specification, whereas in non-strict mode
* it attempts to mimic the exact behaviour of commonly used HTTP agents,
* which many HTTP servers expect.
*
* @param strictMode <tt>true</tt> for strict mode, <tt>false</tt> otherwise
*
* @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
* to exercise a more granular control over HTTP protocol strictness.
*/
public void setStrictMode(boolean strictMode) {
if (strictMode) {
this.params.makeStrict();
} else {
this.params.makeLenient();
}
}
/**
* @deprecated Use {@link org.apache.commons.httpclient.params.HttpParams#setParameter(String, Object)}
* to exercise a more granular control over HTTP protocol strictness.
*
* @return <tt>false</tt>
*/
public boolean isStrictMode() {
return false;
}
/**
* Adds the specified request header, NOT overwriting any previous value.
* Note that header-name matching is case insensitive.
*
* @param headerName the header's name
* @param headerValue the header's value
*/
public void addRequestHeader(String headerName, String headerValue) {
addRequestHeader(new Header(headerName, headerValue));
}
/**
* Tests if the connection should be force-closed when no longer needed.
*
* @return <code>true</code> if the connection must be closed
*/
protected boolean isConnectionCloseForced() {
return this.connectionCloseForced;
}
/**
* Sets whether or not the connection should be force-closed when no longer
* needed. This value should only be set to <code>true</code> in abnormal
* circumstances, such as HTTP protocol violations.
*
* @param b <code>true</code> if the connection must be closed, <code>false</code>
* otherwise.
*/
protected void setConnectionCloseForced(boolean b) {
if (LOG.isDebugEnabled()) {
LOG.debug("Force-close connection: " + b);
}
this.connectionCloseForced = b;
}
/**
* Tests if the connection should be closed after the method has been executed.
* The connection will be left open when using HTTP/1.1 or if <tt>Connection:
* keep-alive</tt> header was sent.
*
* @param conn the connection in question
*
* @return boolean true if we should close the connection.
*/
protected boolean shouldCloseConnection(HttpConnection conn) {
// Connection must be closed due to an abnormal circumstance
if (isConnectionCloseForced()) {
LOG.debug("Should force-close connection.");
return true;
}
Header connectionHeader = null;
// In case being connected via a proxy server
if (!conn.isTransparent()) {
// Check for 'proxy-connection' directive
connectionHeader = responseHeaders.getFirstHeader("proxy-connection");
}
// In all cases Check for 'connection' directive
// some non-complaint proxy servers send it instread of
// expected 'proxy-connection' directive
if (connectionHeader == null) {
connectionHeader = responseHeaders.getFirstHeader("connection");
}
// In case the response does not contain any explict connection
// directives, check whether the request does
if (connectionHeader == null) {
connectionHeader = requestHeaders.getFirstHeader("connection");
}
if (connectionHeader != null) {
if (connectionHeader.getValue().equalsIgnoreCase("close")) {
if (LOG.isDebugEnabled()) {
LOG.debug("Should close connection in response to directive: "
+ connectionHeader.getValue());
}
return true;
} else if (connectionHeader.getValue().equalsIgnoreCase("keep-alive")) {
if (LOG.isDebugEnabled()) {
LOG.debug("Should NOT close connection in response to directive: "
+ connectionHeader.getValue());
}
return false;
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Unknown directive: " + connectionHeader.toExternalForm());
}
}
}
LOG.debug("Resorting to protocol version default close connection policy");
// missing or invalid connection header, do the default
if (this.effectiveVersion.greaterEquals(HttpVersion.HTTP_1_1)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Should NOT close connection, using " + this.effectiveVersion.toString());
}
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("Should close connection, using " + this.effectiveVersion.toString());
}
}
return this.effectiveVersion.lessEquals(HttpVersion.HTTP_1_0);
}
/**
* Tests if the this method is ready to be executed.
*
* @param state the {@link HttpState state} information associated with this method
* @param conn the {@link HttpConnection connection} to be used
* @throws HttpException If the method is in invalid state.
*/
private void checkExecuteConditions(HttpState state, HttpConnection conn)
throws HttpException {
if (state == null) {
throw new IllegalArgumentException("HttpState parameter may not be null");
}
if (conn == null) {
throw new IllegalArgumentException("HttpConnection parameter may not be null");
}
if (this.aborted) {
throw new IllegalStateException("Method has been aborted");
}
if (!validate()) {
throw new ProtocolException("HttpMethodBase object not valid");
}
}
/**
* Executes this method using the specified <code>HttpConnection</code> and
* <code>HttpState</code>.
*
* @param state {@link HttpState state} information to associate with this
* request. Must be non-null.
* @param conn the {@link HttpConnection connection} to used to execute
* this HTTP method. Must be non-null.
*
* @return the integer status code if one was obtained, or <tt>-1</tt>
*
* @throws IOException if an I/O (transport) error occurs
* @throws HttpException if a protocol exception occurs.
*/
public int execute(HttpState state, HttpConnection conn)
throws HttpException, IOException {
LOG.trace("enter HttpMethodBase.execute(HttpState, HttpConnection)");
// this is our connection now, assign it to a local variable so
// that it can be released later
this.responseConnection = conn;
checkExecuteConditions(state, conn);
this.statusLine = null;
this.connectionCloseForced = false;
conn.setLastResponseInputStream(null);
// determine the effective protocol version
if (this.effectiveVersion == null) {
this.effectiveVersion = this.params.getVersion();
}
writeRequest(state, conn);