-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathResponse.java
More file actions
1497 lines (1300 loc) · 41.3 KB
/
Response.java
File metadata and controls
1497 lines (1300 loc) · 41.3 KB
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
/*
* @(#)Response.java 0.3-3 06/05/2001
*
* This file is part of the HTTPClient package
* Copyright (C) 1996-2001 Ronald Tschal�r
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307, USA
*
* For questions, suggestions, bug-reports, enhancement-requests etc.
* I may be contacted at:
*
* ronald@innovation.ch
*
* The HTTPClient's home page is located at:
*
* http://www.innovation.ch/java/HTTPClient/
*/
package HTTPClient;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.EOFException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.ProtocolException;
import java.util.Date;
import java.util.Vector;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.NoSuchElementException;
/**
* This class represents an intermediate response. It's used internally by the
* modules. When all modules have handled the response then the HTTPResponse
* fills in its fields with the data from this class.
*
* @version 0.3-3 06/05/2001
* @author Ronald Tschal�r
*/
public final class Response implements RoResponse, GlobalConstants, Cloneable
{
/** This contains a list of headers which may only have a single value */
private static final Hashtable<String, String> singleValueHeaders;
/** our http connection */
private HTTPConnection connection;
/** our stream demux */
private StreamDemultiplexor stream_handler;
/** the HTTPResponse we're coupled with */
HTTPResponse http_resp;
/** the timeout for read operations */
int timeout = 0;
/** our input stream (usually from the stream demux). Push input streams
* onto this if necessary. */
public InputStream inp_stream;
/** our response input stream from the stream demux */
private RespInputStream resp_inp_stream = null;
/** the method used in the request */
private String method;
/** the resource in the request (for debugging purposes) */
String resource;
/** was a proxy used for the request? */
private boolean used_proxy;
/** did the request contain an entity? */
private boolean sent_entity;
/** the status code returned. */
int StatusCode = 0;
/** the reason line associated with the status code. */
String ReasonLine;
/** the HTTP version of the response. */
String Version;
/** the final URI of the document. */
URI EffectiveURI = null;
/** any headers which were received and do not fit in the above list. */
CIHashtable Headers = new CIHashtable();
/** any trailers which were received and do not fit in the above list. */
CIHashtable Trailers = new CIHashtable();
/** the message length of the response if either there is no data (in which
* case ContentLength=0) or if the message length is controlled by a
* Content-Length header. If neither of these, then it's -1 */
int ContentLength = -1;
/** this indicates how the length of the entity body is determined */
int cd_type = CD_HDRS;
/** the data (body) returned. */
byte[] Data = null;
/** signals if we in the process of reading the headers */
boolean reading_headers = false;
/** signals if we have got and parsed the headers yet */
boolean got_headers = false;
/** signals if we have got and parsed the trailers yet */
boolean got_trailers = false;
/** remembers any exception received while reading/parsing headers */
private IOException exception = null;
/** should this response be handled further? */
boolean final_resp = false;
/** should the request be retried by the application? */
boolean retry = false;
static
{
/* This static initializer creates a hashtable of header names that
* should only have at most a single value in a server response. Other
* headers that may have multiple values (ie Set-Cookie) will have
* their values combined into one header, with individual values being
* separated by commas.
*/
String[] singleValueHeaderNames = {
"age", "location", "content-base", "content-length",
"content-location", "content-md5", "content-range", "content-type",
"date", "etag", "expires", /*"proxy-authenticate",*/ "retry-after",
};
// @Gusbro:
// @HACK: Por alguna razon esta puesto que el proxy-authenticate solo banque
// uno solo tipo. Lo saco para que se banque varios esquemas de autenticacion
// a la vez
singleValueHeaders = new Hashtable<>(singleValueHeaderNames.length);
for (int idx=0; idx<singleValueHeaderNames.length; idx++)
singleValueHeaders.put(singleValueHeaderNames[idx],
singleValueHeaderNames[idx]);
}
// Constructors
/**
* Creates a new Response and registers it with the stream-demultiplexor.
*/
Response(Request request, boolean used_proxy,
StreamDemultiplexor stream_handler)
throws IOException
{
this.connection = request.getConnection();
this.method = request.getMethod();
this.resource = request.getRequestURI();
this.used_proxy = used_proxy;
this.stream_handler = stream_handler;
sent_entity = (request.getData() != null) ? true : false;
stream_handler.register(this, request);
resp_inp_stream = stream_handler.getStream(this);
inp_stream = resp_inp_stream;
}
/**
* Creates a new Response that reads from the given stream. This is
* used for the CONNECT subrequest which is used in establishing an
* SSL tunnel through a proxy.
*
* @param request the subrequest
* @param is the input stream from which to read the headers and
* data.
*/
Response(Request request, InputStream is) throws IOException
{
this.connection = request.getConnection();
this.method = request.getMethod();
this.resource = request.getRequestURI();
used_proxy = false;
stream_handler = null;
sent_entity = (request.getData() != null) ? true : false;
inp_stream = is;
}
/**
* Create a new response with the given info. This is used when
* creating a response in a requestHandler().
*
* <P>If <var>data</var> is not null then that is used; else if the
* <var>is</var> is not null that is used; else the entity is empty.
* If the input stream is used then <var>cont_len</var> specifies
* the length of the data that can be read from it, or -1 if unknown.
*
* @param version the response version (such as "HTTP/1.1")
* @param status the status code
* @param reason the reason line
* @param headers the response headers
* @param data the response entity
* @param is the response entity as an InputStream
* @param cont_len the length of the data in the InputStream
*/
public Response(String version, int status, String reason, NVPair[] headers,
byte[] data, InputStream is, int cont_len)
{
this.Version = version;
this.StatusCode = status;
this.ReasonLine = reason;
if (headers != null)
for (int idx=0; idx<headers.length; idx++)
setHeader(headers[idx].getName(), headers[idx].getValue());
if (data != null)
this.Data = data;
else if (is == null)
this.Data = new byte[0];
else
{
this.inp_stream = is;
ContentLength = cont_len;
}
got_headers = true;
got_trailers = true;
}
// Methods
/**
* give the status code for this request. These are grouped as follows:
* <UL>
* <LI> 1xx - Informational (new in HTTP/1.1)
* <LI> 2xx - Success
* <LI> 3xx - Redirection
* <LI> 4xx - Client Error
* <LI> 5xx - Server Error
* </UL>
*
* @exception IOException If any exception occurs on the socket.
*/
public final int getStatusCode() throws IOException
{
if (!got_headers) getHeaders(true);
return StatusCode;
}
/**
* give the reason line associated with the status code.
*
* @exception IOException If any exception occurs on the socket.
*/
public final String getReasonLine() throws IOException
{
if (!got_headers) getHeaders(true);
return ReasonLine;
}
/**
* get the HTTP version used for the response.
*
* @exception IOException If any exception occurs on the socket.
*/
public final String getVersion() throws IOException
{
if (!got_headers) getHeaders(true);
return Version;
}
/**
* Wait for either a '100 Continue' or an error.
*
* @return the return status.
*/
int getContinue() throws IOException
{
getHeaders(false);
return StatusCode;
}
/**
* get the final URI of the document. This is set if the original
* request was deferred via the "moved" (301, 302, or 303) return
* status.
*
* @return the new URI, or null if not redirected
* @exception IOException If any exception occurs on the socket.
*/
public final URI getEffectiveURI() throws IOException
{
if (!got_headers) getHeaders(true);
return EffectiveURI;
}
/**
* set the final URI of the document. This is only for internal use.
*/
public void setEffectiveURI(URI final_uri)
{
EffectiveURI = final_uri;
}
/**
* get the final URL of the document. This is set if the original
* request was deferred via the "moved" (301, 302, or 303) return
* status.
*
* @exception IOException If any exception occurs on the socket.
* @deprecated use getEffectiveURI() instead
* @see #getEffectiveURI
*/
public final URL getEffectiveURL() throws IOException
{
return getEffectiveURI().toURL();
}
/**
* set the final URL of the document. This is only for internal use.
*
* @deprecated use setEffectiveURI() instead
* @see #setEffectiveURI
*/
public void setEffectiveURL(URL final_url)
{
try
{ setEffectiveURI(new URI(final_url)); }
catch (ParseException pe)
{ throw new Error(pe.toString()); } // shouldn't happen
}
/**
* retrieves the field for a given header.
*
* @param hdr the header name.
* @return the value for the header, or null if non-existent.
* @exception IOException If any exception occurs on the socket.
*/
public String getHeader(String hdr) throws IOException
{
if (!got_headers) getHeaders(true);
return (String) Headers.get(hdr.trim());
}
/**
* retrieves the field for a given header. The value is parsed as an
* int.
*
* @param hdr the header name.
* @return the value for the header if the header exists
* @exception NumberFormatException if the header's value is not a number
* or if the header does not exist.
* @exception IOException if any exception occurs on the socket.
*/
public int getHeaderAsInt(String hdr)
throws IOException, NumberFormatException
{
String val = getHeader(hdr);
if (val == null)
throw new NumberFormatException("null");
return Integer.parseInt(val);
}
/**
* retrieves the field for a given header. The value is parsed as a
* date; if this fails it is parsed as a long representing the number
* of seconds since 12:00 AM, Jan 1st, 1970. If this also fails an
* IllegalArgumentException is thrown.
*
* <P>Note: When sending dates use Util.httpDate().
*
* @param hdr the header name.
* @return the value for the header, or null if non-existent.
* @exception IOException If any exception occurs on the socket.
* @exception IllegalArgumentException If the header cannot be parsed
* as a date or time.
*/
public Date getHeaderAsDate(String hdr)
throws IOException, IllegalArgumentException
{
String raw_date = getHeader(hdr);
if (raw_date == null) return null;
// asctime() format is missing an explicit GMT specifier
if (raw_date.toUpperCase().indexOf("GMT") == -1 &&
raw_date.indexOf(' ') > 0)
raw_date += " GMT";
Date date;
try
{ date = Util.parseHttpDate(raw_date); }
catch (IllegalArgumentException iae)
{
long time;
try
{ time = Long.parseLong(raw_date); }
catch (NumberFormatException nfe)
{ throw iae; }
if (time < 0) time = 0;
date = new Date(time * 1000L);
}
return date;
}
/**
* Set a header field in the list of headers. If the header already
* exists it will be overwritten; otherwise the header will be added
* to the list. This is used by some modules when they process the
* header so that higher level stuff doesn't get confused when the
* headers and data don't match.
*
* @param header The name of header field to set.
* @param value The value to set the field to.
*/
public void setHeader(String header, String value)
{
Headers.put(header.trim(), value.trim());
}
/**
* Removes a header field from the list of headers. This is used by
* some modules when they process the header so that higher level stuff
* doesn't get confused when the headers and data don't match.
*
* @param header The name of header field to remove.
*/
public void deleteHeader(String header)
{
Headers.remove(header.trim());
}
/**
* Retrieves the field for a given trailer. Note that this should not
* be invoked until all the response data has been read. If invoked
* before, it will force the data to be read via <code>getData()</code>.
*
* @param trailer the trailer name.
* @return the value for the trailer, or null if non-existent.
* @exception IOException If any exception occurs on the socket.
*/
public String getTrailer(String trailer) throws IOException
{
if (!got_trailers) getTrailers();
return (String) Trailers.get(trailer.trim());
}
/**
* Retrieves the field for a given tailer. The value is parsed as an
* int.
*
* @param trailer the tailer name.
* @return the value for the trailer if the trailer exists
* @exception NumberFormatException if the trailer's value is not a number
* or if the trailer does not exist.
* @exception IOException if any exception occurs on the socket.
*/
public int getTrailerAsInt(String trailer)
throws IOException, NumberFormatException
{
String val = getTrailer(trailer);
if (val == null)
throw new NumberFormatException("null");
return Integer.parseInt(val);
}
/**
* Retrieves the field for a given trailer. The value is parsed as a
* date; if this fails it is parsed as a long representing the number
* of seconds since 12:00 AM, Jan 1st, 1970. If this also fails an
* IllegalArgumentException is thrown.
*
* <P>Note: When sending dates use Util.httpDate().
*
* @param trailer the trailer name.
* @return the value for the trailer, or null if non-existent.
* @exception IllegalArgumentException if the trailer's value is neither a
* legal date nor a number.
* @exception IOException if any exception occurs on the socket.
* @exception IllegalArgumentException If the header cannot be parsed
* as a date or time.
*/
public Date getTrailerAsDate(String trailer)
throws IOException, IllegalArgumentException
{
String raw_date = getTrailer(trailer);
if (raw_date == null) return null;
// asctime() format is missing an explicit GMT specifier
if (raw_date.toUpperCase().indexOf("GMT") == -1 &&
raw_date.indexOf(' ') > 0)
raw_date += " GMT";
Date date;
try
{ date = Util.parseHttpDate(raw_date); }
catch (IllegalArgumentException iae)
{
// some servers erroneously send a number, so let's try that
long time;
try
{ time = Long.parseLong(raw_date); }
catch (NumberFormatException nfe)
{ throw iae; } // give up
if (time < 0) time = 0;
date = new Date(time * 1000L);
}
return date;
}
/**
* Set a trailer field in the list of trailers. If the trailer already
* exists it will be overwritten; otherwise the trailer will be added
* to the list. This is used by some modules when they process the
* trailer so that higher level stuff doesn't get confused when the
* trailer and data don't match.
*
* @param trailer The name of trailer field to set.
* @param value The value to set the field to.
*/
public void setTrailer(String trailer, String value)
{
Trailers.put(trailer.trim(), value.trim());
}
/**
* Removes a trailer field from the list of trailers. This is used by
* some modules when they process the trailer so that higher level stuff
* doesn't get confused when the trailers and data don't match.
*
* @param trailer The name of trailer field to remove.
*/
public void deleteTrailer(String trailer)
{
Trailers.remove(trailer.trim());
}
/**
* Reads all the response data into a byte array. Note that this method
* won't return until <em>all</em> the data has been received (so for
* instance don't invoke this method if the server is doing a server
* push). If getInputStream() had been previously called then this method
* only returns any unread data remaining on the stream and then closes
* it.
*
* @see #getInputStream()
* @return an array containing the data (body) returned. If no data
* was returned then it's set to a zero-length array.
* @exception IOException If any io exception occured while reading
* the data
*/
public synchronized byte[] getData() throws IOException
{
if (!got_headers) getHeaders(true);
if (Data == null)
{
try
{ readResponseData(inp_stream); }
catch (InterruptedIOException ie) // don't intercept
{ throw ie; }
catch (IOException ioe)
{
Log.write(Log.RESP, "Resp: (" + inp_stream.hashCode() + ")",
ioe);
try { inp_stream.close(); } catch (Exception e) { }
throw ioe;
}
inp_stream.close();
}
return Data;
}
/**
* Gets an input stream from which the returned data can be read. Note
* that if getData() had been previously called it will actually return
* a ByteArrayInputStream created from that data.
*
* @see #getData()
* @return the InputStream.
* @exception IOException If any exception occurs on the socket.
*/
public synchronized InputStream getInputStream() throws IOException
{
if (!got_headers) getHeaders(true);
if (Data == null)
return inp_stream;
else
return new ByteArrayInputStream(Data);
}
/**
* Some responses such as those from a HEAD or with certain status
* codes don't have an entity. This is detected by the client and
* can be queried here. Note that this won't try to do a read() on
* the input stream (it will however cause the headers to be read
* and parsed if not already done).
*
* @return true if the response has an entity, false otherwise
* @since V0.3-1
*/
public synchronized boolean hasEntity() throws IOException
{
if (!got_headers) getHeaders(true);
return (cd_type != CD_0);
}
/**
* Should the request be retried by the application? This can be used
* by modules to signal to the application that it should retry the
* request. It's used when the request used an <var>HttpOutputStream</var>
* and the module is therefore not able to retry the request itself.
* This flag is <var>false</var> by default.
*
* <P>If a module sets this flag then it must also reset() the
* the <var>HttpOutputStream</var> so it may be reused by the application.
* It should then also use this <var>HttpOutputStream</var> to recognize
* the retried request in the requestHandler().
*
* @param flag indicates whether the application should retry the request.
*/
public void setRetryRequest(boolean flag)
{
retry = flag;
}
/**
* @return true if the request should be retried.
*/
public boolean retryRequest()
{
return retry;
}
// Helper Methods
/**
* Gets and parses the headers. Sets up Data if no data will be received.
*
* @param skip_cont if true skips over '100 Continue' status codes.
* @exception IOException If any exception occurs while reading the headers.
*/
private synchronized void getHeaders(boolean skip_cont) throws IOException
{
if (got_headers) return;
if (exception != null)
{
exception.fillInStackTrace();
throw exception;
}
reading_headers = true;
try
{
do
{
Headers.clear(); // clear any headers from 100 Continue
String headers = readResponseHeaders(inp_stream);
parseResponseHeaders(headers);
} while ((StatusCode == 100 && skip_cont) || // Continue
(StatusCode > 101 && StatusCode < 200)); // Unknown
}
catch (IOException ioe)
{
if (!(ioe instanceof InterruptedIOException))
exception = ioe;
if (ioe instanceof ProtocolException) // thrown internally
{
cd_type = CD_CLOSE;
if (stream_handler != null)
stream_handler.markForClose(this);
}
throw ioe;
}
finally
{ reading_headers = false; }
if (StatusCode == 100) return;
// parse the Content-Length header
int cont_len = -1;
String cl_hdr = (String) Headers.get("Content-Length");
if (cl_hdr != null)
{
try
{
cont_len = Integer.parseInt(cl_hdr);
if (cont_len < 0)
throw new NumberFormatException();
}
catch (NumberFormatException nfe)
{
throw new ProtocolException("Invalid Content-length header"+
" received: "+cl_hdr);
}
}
// parse the Transfer-Encoding header
boolean te_chunked = false, te_is_identity = true, ct_mpbr = false;
Vector<HttpHeaderElement> te_hdr = null;
try
{ te_hdr = Util.parseHeader((String) Headers.get("Transfer-Encoding")); }
catch (ParseException pe)
{ }
if (te_hdr != null)
{
te_chunked = te_hdr.lastElement().getName().
equalsIgnoreCase("chunked");
for (int idx=0; idx<te_hdr.size(); idx++)
if (te_hdr.elementAt(idx).getName().
equalsIgnoreCase("identity"))
te_hdr.removeElementAt(idx--);
else
te_is_identity = false;
}
// parse Content-Type header
try
{
String hdr;
if ((hdr = (String) Headers.get("Content-Type")) != null)
{
Vector phdr = Util.parseHeader(hdr);
ct_mpbr = phdr.contains(new HttpHeaderElement("multipart/byteranges")) ||
phdr.contains(new HttpHeaderElement("multipart/x-byteranges"));
}
}
catch (ParseException pe)
{ }
// now determine content-delimiter
if (StatusCode < 200 || StatusCode == 204 || StatusCode == 205 ||
StatusCode == 304)
{
cd_type = CD_0;
}
else if (te_chunked)
{
cd_type = CD_CHUNKED;
te_hdr.removeElementAt(te_hdr.size()-1);
if (te_hdr.size() > 0)
setHeader("Transfer-Encoding", Util.assembleHeader(te_hdr));
else
deleteHeader("Transfer-Encoding");
}
else if (cont_len != -1 && te_is_identity)
cd_type = CD_CONTLEN;
else if (ct_mpbr && te_is_identity)
cd_type = CD_MP_BR;
else if (!method.equals("HEAD"))
{
cd_type = CD_CLOSE;
if (stream_handler != null)
stream_handler.markForClose(this);
if (Version.equals("HTTP/0.9"))
{
inp_stream =
new SequenceInputStream(new ByteArrayInputStream(Data),
inp_stream);
Data = null;
}
}
if (cd_type == CD_CONTLEN)
ContentLength = cont_len;
else
deleteHeader("Content-Length"); // Content-Length is not valid in this case
/* We treat HEAD specially down here because the above code needs
* to know whether to remove the Content-length header or not.
*/
if (method.equals("HEAD"))
cd_type = CD_0;
if (cd_type == CD_0)
{
ContentLength = 0;
Data = new byte[0];
inp_stream.close(); // we will not receive any more data
}
Log.write(Log.RESP, "Resp: Response entity delimiter: " +
(cd_type == CD_0 ? "No Entity" :
cd_type == CD_CLOSE ? "Close" :
cd_type == CD_CONTLEN ? "Content-Length" :
cd_type == CD_CHUNKED ? "Chunked" :
cd_type == CD_MP_BR ? "Multipart" :
"???" ) + " (" + inp_stream.hashCode() + ")");
// remove erroneous connection tokens
if (connection.ServerProtocolVersion >= HTTP_1_1)
deleteHeader("Proxy-Connection");
else // HTTP/1.0
{
if (connection.getProxyHost() != null)
deleteHeader("Connection");
else
deleteHeader("Proxy-Connection");
Vector<HttpHeaderElement> pco;
try
{ pco = Util.parseHeader((String) Headers.get("Connection")); }
catch (ParseException pe)
{ pco = null; }
if (pco != null)
{
for (int idx=0; idx<pco.size(); idx++)
{
String name =
pco.elementAt(idx).getName();
if (!name.equalsIgnoreCase("keep-alive"))
{
pco.removeElementAt(idx);
deleteHeader(name);
idx--;
}
}
if (pco.size() > 0)
setHeader("Connection", Util.assembleHeader(pco));
else
deleteHeader("Connection");
}
try
{ pco = Util.parseHeader((String) Headers.get("Proxy-Connection")); }
catch (ParseException pe)
{ pco = null; }
if (pco != null)
{
for (int idx=0; idx<pco.size(); idx++)
{
String name =
pco.elementAt(idx).getName();
if (!name.equalsIgnoreCase("keep-alive"))
{
pco.removeElementAt(idx);
deleteHeader(name);
idx--;
}
}
if (pco.size() > 0)
setHeader("Proxy-Connection", Util.assembleHeader(pco));
else
deleteHeader("Proxy-Connection");
}
}
// this must be set before we invoke handleFirstRequest()
got_headers = true;
// special handling if this is the first response received
if (isFirstResponse)
{
if (!connection.handleFirstRequest(req, this))
{
// got a buggy server - need to redo the request
Response resp;
try
{ resp = connection.sendRequest(req, timeout); }
catch (ModuleException me)
{ throw new IOException(me.toString()); }
resp.getVersion();
this.StatusCode = resp.StatusCode;
this.ReasonLine = resp.ReasonLine;
this.Version = resp.Version;
this.EffectiveURI = resp.EffectiveURI;
this.ContentLength = resp.ContentLength;
this.Headers = resp.Headers;
this.inp_stream = resp.inp_stream;
this.Data = resp.Data;
req = null;
}
}
}
/* these are external to readResponseHeaders() because we need to be
* able to restart after an InterruptedIOException
*/
private byte[] buf = new byte[7];
private int buf_pos = 0;
private StringBuffer hdrs = new StringBuffer(400);
private boolean reading_lines = false;
private boolean bol = true;
private boolean got_cr = false;
/**
* Reads the response headers received, folding continued lines.
*
* <P>Some of the code is a bit convoluted because we have to be able
* restart after an InterruptedIOException.
*
* @inp the input stream from which to read the response
* @return a (newline separated) list of headers
* @exception IOException if any read on the input stream fails
*/
private String readResponseHeaders(InputStream inp) throws IOException
{
if (buf_pos == 0)
Log.write(Log.RESP, "Resp: Reading Response headers " +
inp_stream.hashCode());
else
Log.write(Log.RESP, "Resp: Resuming reading Response headers " +
inp_stream.hashCode());
// read 7 bytes to see type of response
if (!reading_lines)
{
try
{
// Skip any leading white space to accomodate buggy responses
if (buf_pos == 0)
{
int c;
do
{
if ((c = inp.read()) == -1)
throw new EOFException("Encountered premature EOF "
+ "while reading Version");
} while (Character.isWhitespace((char) c)) ;
buf[0] = (byte) c;
buf_pos = 1;
}
// Now read first seven bytes (the version string)
while (buf_pos < buf.length)
{
int got = inp.read(buf, buf_pos, buf.length-buf_pos);
if (got == -1)
throw new EOFException("Encountered premature EOF " +
"while reading Version");
buf_pos += got;
}
}
catch (EOFException eof)
{
Log.write(Log.RESP, "Resp: (" + inp_stream.hashCode() + ")",
eof);
throw eof;
}
for (int idx=0; idx<buf.length; idx++)