-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathHTTPConnection.java
More file actions
4180 lines (3626 loc) · 130 KB
/
HTTPConnection.java
File metadata and controls
4180 lines (3626 loc) · 130 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
/*
* @(#)HTTPConnection.java 0.3-3I 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.OutputStream;
import java.io.DataOutputStream;
import java.io.FilterOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.URL;
import java.net.Socket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.net.NoRouteToHostException;
import java.util.Vector;
import java.util.StringTokenizer;
/**
* This class implements http protocol requests; it contains most of HTTP/1.1
* and ought to be unconditionally compliant.
* Redirections are automatically handled, and authorizations requests are
* recognized and dealt with via an authorization handler.
* Only full HTTP/1.0 and HTTP/1.1 requests are generated. HTTP/1.1, HTTP/1.0
* and HTTP/0.9 responses are recognized.
*
* <P>Using the HTTPClient should be quite simple. First add the import
* statement '<code>import HTTPClient.*;</code>' to your file(s). Request
* can then be sent using one of the methods <var>Head()</var>,
* <var>Get()</var>, <var>Post()</var>, etc in <var>HTTPConnection</var>.
* These methods all return an instance of <var>HTTPResponse</var> which
* has methods for accessing the response headers (<var>getHeader()</var>,
* <var>getHeaderAsInt()</var>, etc), various response info
* (<var>getStatusCode()</var>, <var>getReasonLine()</var>, etc) and the
* reponse data (<var>getData()</var>, <var>getText()</var>, and
* <var>getInputStream()</var>). Following are some examples.
*
* <P>If this is in an applet you can retrieve files from your server
* as follows:
*
* <PRE>
* try
* {
* HTTPConnection con = new HTTPConnection(this);
* HTTPResponse rsp = con.Get("/my_file");
* if (rsp.getStatusCode() >= 300)
* {
* System.err.println("Received Error: "+rsp.getReasonLine());
* System.err.println(rsp.getText());
* }
* else
* data = rsp.getData();
*
* rsp = con.Get("/another_file");
* if (rsp.getStatusCode() >= 300)
* {
* System.err.println("Received Error: "+rsp.getReasonLine());
* System.err.println(rsp.getText());
* }
* else
* other_data = rsp.getData();
* }
* catch (IOException ioe)
* {
* System.err.println(ioe.toString());
* }
* catch (ModuleException me)
* {
* System.err.println("Error handling request: " + me.getMessage());
* }
* </PRE>
*
* This will get the files "/my_file" and "/another_file" and put their
* contents into byte[]'s accessible via <code>getData()</code>. Note that
* you need to only create a new <var>HTTPConnection</var> when sending a
* request to a new server (different host or port); although you may create
* a new <var>HTTPConnection</var> for every request to the same server this
* <strong>not</strong> recommended, as various information about the server
* is cached after the first request (to optimize subsequent requests) and
* persistent connections are used whenever possible.
*
* <P>To POST form data you would use something like this (assuming you
* have two fields called <var>name</var> and <var>e-mail</var>, whose
* contents are stored in the variables <var>name</var> and <var>email</var>):
*
* <PRE>
* try
* {
* NVPair form_data[] = new NVPair[2];
* form_data[0] = new NVPair("name", name);
* form_data[1] = new NVPair("e-mail", email);
*
* HTTPConnection con = new HTTPConnection(this);
* HTTPResponse rsp = con.Post("/cgi-bin/my_script", form_data);
* if (rsp.getStatusCode() >= 300)
* {
* System.err.println("Received Error: "+rsp.getReasonLine());
* System.err.println(rsp.getText());
* }
* else
* stream = rsp.getInputStream();
* }
* catch (IOException ioe)
* {
* System.err.println(ioe.toString());
* }
* catch (ModuleException me)
* {
* System.err.println("Error handling request: " + me.getMessage());
* }
* </PRE>
*
* Here the response data is read at leasure via an <var>InputStream</var>
* instead of all at once into a <var>byte[]</var>.
*
* <P>As another example, if you have a URL you're trying to send a request
* to you would do something like the following:
*
* <PRE>
* try
* {
* URL url = new URL("http://www.mydomain.us/test/my_file");
* HTTPConnection con = new HTTPConnection(url);
* HTTPResponse rsp = con.Put(url.getFile(), "Hello World");
* if (rsp.getStatusCode() >= 300)
* {
* System.err.println("Received Error: "+rsp.getReasonLine());
* System.err.println(rsp.getText());
* }
* else
* text = rsp.getText();
* }
* catch (IOException ioe)
* {
* System.err.println(ioe.toString());
* }
* catch (ModuleException me)
* {
* System.err.println("Error handling request: " + me.getMessage());
* }
* </PRE>
*
* <P>There are a whole number of methods for each request type; however the
* general forms are ([...] means that the enclosed is optional):
* <ul>
* <li> Head ( file [, form-data [, headers ] ] )
* <li> Head ( file [, query [, headers ] ] )
* <li> Get ( file [, form-data [, headers ] ] )
* <li> Get ( file [, query [, headers ] ] )
* <li> Post ( file [, form-data [, headers ] ] )
* <li> Post ( file [, data [, headers ] ] )
* <li> Post ( file [, stream [, headers ] ] )
* <li> Put ( file , data [, headers ] )
* <li> Put ( file , stream [, headers ] )
* <li> Delete ( file [, headers ] )
* <li> Options ( file [, headers [, data] ] )
* <li> Options ( file [, headers [, stream] ] )
* <li> Trace ( file [, headers ] )
* </ul>
*
* @version 0.3-3I 06/05/2001
* @author Ronald Tschal�r
*/
public class HTTPConnection implements GlobalConstants, HTTPClientModuleConstants
{
/** The current version of this package. */
public final static String version = "RPT-HTTPClient/0.3-3I";
/** The default context */
private final static Object dflt_context = new Object();
/** The current context */
private Object Context = null;
/** The protocol used on this connection */
private int Protocol;
/** The server's protocol version; M.m stored as (M<<16 | m) */
int ServerProtocolVersion;
/** Have we gotten the server's protocol version yet? */
boolean ServProtVersKnown;
/** The protocol version we send in a request; this is always HTTP/1.1
unless we're talking to a broken server in which case it's HTTP/1.0 */
private String RequestProtocolVersion;
/** The remote host this connection is associated with */
private String Host;
/** The remote port this connection is attached to */
private int Port;
/** The local address this connection is associated with */
private InetAddress LocalAddr;
/** The local port this connection is attached to */
private int LocalPort;
/** The current proxy host to use (if any) */
private String Proxy_Host = null;
/** The current proxy port */
private int Proxy_Port;
/** The default proxy host to use (if any) */
private static String Default_Proxy_Host = null;
/** The default proxy port */
private static int Default_Proxy_Port;
/** The list of hosts for which no proxy is to be used */
private static CIHashtable non_proxy_host_list = new CIHashtable();
private static Vector<String> non_proxy_dom_list = new Vector<>();
private static Vector<byte[]> non_proxy_addr_list = new Vector<>();
private static Vector<byte[]> non_proxy_mask_list = new Vector<>();
/** The socks server to use */
private SocksClient Socks_client = null;
/** The default socks server to use */
private static SocksClient Default_Socks_client = null;
/** the current stream demultiplexor */
private StreamDemultiplexor input_demux = null;
/** a list of active stream demultiplexors */
LinkedList DemuxList = new LinkedList();
/** a list of active requests */
private LinkedList RequestList = new LinkedList();
/** does the server support keep-alive's? */
private boolean doesKeepAlive = false;
/** have we been able to determine the above yet? */
private boolean keepAliveUnknown = true;
/** the maximum number of requests over a HTTP/1.0 keep-alive connection */
private int keepAliveReqMax = -1;
/** the number of requests over a HTTP/1.0 keep-alive connection left */
private int keepAliveReqLeft;
/** hack to force buffering of data instead of using chunked T-E */
private static boolean no_chunked = false;
/** hack to force HTTP/1.0 requests */
private static boolean force_1_0 = false;
/** hack to be able to disable pipelining */
private static boolean neverPipeline = false;
/** hack to be able to disable keep-alives */
private static boolean noKeepAlives = false;
/** hack to work around M$ bug */
private static boolean haveMSLargeWritesBug = false;
/** hack to only enable defered handling of streamed requests when
* configured to do so. */
static boolean deferStreamed = false;
/** the default timeout to use for new connections */
private static int DefaultTimeout = 0;
/** the timeout to use for reading responses */
private int Timeout;
/** The list of default http headers */
private NVPair[] DefaultHeaders = new NVPair[0];
/** The default list of modules (as a Vector of Class objects) */
private static Vector<Class<?>> DefaultModuleList;
/** The list of modules (as a Vector of Class objects) */
private Vector<Class<?>> ModuleList;
/** controls whether modules are allowed to interact with user */
private static boolean defaultAllowUI = true;
/** controls whether modules are allowed to interact with user */
private boolean allowUI;
private ISSLConnection sslConnection = new DefaultSSLConnection();
//@iroqueta
private boolean tcpNoDelay = false;
private boolean includeCookies = true;
/** IAIK's SSL context */
// private SSLContext ssl_ctxt;
static
{
/*
* Let's try and see if we can figure out whether any proxies are
* being used.
*/
try // JDK 1.1 naming
{
String host = System.getProperty("http.proxyHost");
if (host == null)
throw new Exception(); // try JDK 1.0.x naming
int port = Integer.getInteger("http.proxyPort", -1).intValue();
Log.write(Log.CONN, "Conn: using proxy " + host + ":" + port);
setProxyServer(host, port);
}
catch (Exception e)
{
try // JDK 1.0.x naming
{
if (Boolean.getBoolean("proxySet"))
{
String host = System.getProperty("proxyHost");
int port = Integer.getInteger("proxyPort", -1).intValue();
Log.write(Log.CONN, "Conn: using proxy " + host + ":" + port);
setProxyServer(host, port);
}
}
catch (Exception ee)
{ Default_Proxy_Host = null; }
}
/*
* now check for the non-proxy list
*/
try
{
String hosts = System.getProperty("HTTPClient.nonProxyHosts");
if (hosts == null)
hosts = System.getProperty("http.nonProxyHosts");
String[] list = Util.splitProperty(hosts);
dontProxyFor(list);
}
catch (Exception e)
{ }
/*
* we can't turn the JDK SOCKS handling off, so we don't use the
* properties 'socksProxyHost' and 'socksProxyPort'. Instead we
* define 'HTTPClient.socksHost', 'HTTPClient.socksPort' and
* 'HTTPClient.socksVersion'.
*/
try
{
String host = System.getProperty("HTTPClient.socksHost");
if (host != null && host.length() > 0)
{
int port = Integer.getInteger("HTTPClient.socksPort", -1).intValue();
int version = Integer.getInteger("HTTPClient.socksVersion", -1).intValue();
Log.write(Log.CONN, "Conn: using SOCKS " + host + ":" + port);
if (version == -1)
setSocksServer(host, port);
else
setSocksServer(host, port, version);
}
}
catch (Exception e)
{ Default_Socks_client = null; }
// Set up module list
String modules = "HTTPClient.RetryModule|" +
"HTTPClient.CookieModule|" +
"HTTPClient.RedirectionModule|" +
"HTTPClient.AuthorizationModule|" +
"HTTPClient.DefaultModule|" +
"HTTPClient.TransferEncodingModule|" +
"HTTPClient.ContentMD5Module|" +
"HTTPClient.ContentEncodingModule";
boolean in_applet = false;
try
{ modules = System.getProperty("HTTPClient.Modules", modules); }
catch (SecurityException se)
{ in_applet = true; }
DefaultModuleList = new Vector<>();
String[] list = Util.splitProperty(modules);
for (int idx=0; idx<list.length; idx++)
{
try
{
DefaultModuleList.addElement(Class.forName(list[idx]));
Log.write(Log.CONN, "Conn: added module " + list[idx]);
}
catch (ClassNotFoundException cnfe)
{
if (!in_applet)
throw new NoClassDefFoundError(cnfe.getMessage());
/* Just ignore it. This allows for example applets to just
* load the necessary modules - if you don't need a module
* then don't provide it, and it won't be added to the
* list. The disadvantage is that if you accidently misstype
* a module name this will lead to a "silent" error.
*/
}
}
/*
* Hack: disable pipelining
*/
try
{
neverPipeline = Boolean.getBoolean("HTTPClient.disable_pipelining");
if (neverPipeline)
Log.write(Log.CONN, "Conn: disabling pipelining");
neverPipeline = true;
}
catch (Exception e)
{ }
/*
* Hack: disable keep-alives
*/
try
{
noKeepAlives = Boolean.getBoolean("HTTPClient.disableKeepAlives");
if (noKeepAlives)
Log.write(Log.CONN, "Conn: disabling keep-alives");
}
catch (Exception e)
{ }
/*
* Hack: force HTTP/1.0 requests
*/
try
{
force_1_0 = Boolean.getBoolean("HTTPClient.forceHTTP_1.0");
if (force_1_0)
Log.write(Log.CONN, "Conn: forcing HTTP/1.0 requests");
}
catch (Exception e)
{ }
/*
* Hack: prevent chunking of request data
*/
try
{
no_chunked = Boolean.getBoolean("HTTPClient.dontChunkRequests");
if (no_chunked)
Log.write(Log.CONN, "Conn: never chunking requests");
}
catch (Exception e)
{ }
/*
* M$ bug: large writes hang the stuff
*/
try
{
if (System.getProperty("os.name").indexOf("Windows") >= 0 &&
System.getProperty("java.version").startsWith("1.1"))
haveMSLargeWritesBug = true;
if (haveMSLargeWritesBug)
Log.write(Log.CONN, "Conn: splitting large writes into 20K chunks (M$ bug)");
}
catch (Exception e)
{ }
/*
* Deferring the handling of responses to requests which used an output
* stream is new in V0.3-3. Because it can cause memory leaks for apps
* which aren't expecting this, we only enable this feature if
* explicitly requested to do so.
*/
try
{
deferStreamed = Boolean.getBoolean("HTTPClient.deferStreamed");
if (deferStreamed)
Log.write(Log.CONN, "Conn: enabling defered handling of " +
"responses to streamed requests");
}
catch (Exception e)
{ }
}
static
{
/**
* @gusbro: Agregamos el pasaje por SystemProperties de una lista de User/Pass
* La SystemProperty con la lista de autenticaciones se llama 'HTTPClient.authenticationList'
* El formato es el siguiente: auth1;auth2;auth3;...
* donde authX es: tipo(NTLM,Digest o Basic),server(o host),puerto,realm,user,password
* Por ejemplo, authX podr�a ser: NTLM,http://myserver/dir,9090,,ISA-SRV\gusbro,mipass
* u otro ejemplo: Basic,myserver,8080,realm,gusbro,pepito
*/
try
{
String authList = System.getProperty("HTTPClient.authenticationList", null);
if(authList != null)
{
if(authList.startsWith("@"))authList = descramble(authList.substring(1)); // Le hago un descramble si el primer caracter es @
StringTokenizer tok = new StringTokenizer(authList, ";");
while(tok.hasMoreTokens())
{
String token = tok.nextToken().trim();
while(token.indexOf(",,")!= -1)token = token.substring(0,token.indexOf(",,")) + ",''" + token.substring(token.indexOf(",,") + 1);
StringTokenizer authInfo = new StringTokenizer(token, ",");
if(authInfo.countTokens() >= 6)
{
String method = authInfo.nextToken();
String server = authInfo.nextToken();
if(server.indexOf("://") == -1)server = "http://" + server;
URL url = new URL(server);
String host = url.getHost();
int port = new Integer(authInfo.nextToken()).intValue();
String realm = authInfo.nextToken();
if(realm.equals("''"))realm = "";
String user = authInfo.nextToken();
String password = authInfo.nextToken();
if(method.equalsIgnoreCase("NTLM"))
{
AuthorizationInfo.addNTLMAuthorization(host, port, realm, user, password);
}else
{
if(method.equalsIgnoreCase("Digest"))
{
AuthorizationInfo.addDigestAuthorization(host, port, realm, user, password);
}
else
{
AuthorizationInfo.addBasicAuthorization(host, port, realm, user, password);
}
}
}
}
}
}catch(Exception e) { ; }
}
//@gusbro
public static int getDefaultProxyPort()
{
return Default_Proxy_Port;
}
public static String getDefaultProxyHost()
{
return Default_Proxy_Host;
}
/** Realiza el scramble del String pasado como par�metro
* Realizo un byte stuffing en el caso de que el byte resultado sea < 34
* En el caso de que el byte sea < 34, inserto un byte '\33' y luego el byte + 128
* @param data String a encriptar
* @return String enciptado
*/
public static String scramble(String data)
{
if(data == null) return null; // Si el String a encriptar es null, no hago nada
byte [] SCRATCH = ("HTTPClient-tneilCPTTH").getBytes(); // Bytes utilizados en el Scramble de datos
String ret = "";
int tempSize = data.length();
int scratch_size = SCRATCH.length;
char []tempData = data.toCharArray();
for(int i = 0 ; i < tempData.length; i++)
{
char temp = (char)(tempData[i] ^ SCRATCH[(tempSize++) % scratch_size]);
if(temp < 37) // Debo hacer byte stuffing
{
ret += (char) 36;
temp += 37;
}
ret += temp;
}
return ret;
}
/** Realiza el descramble de un String encriptado
* @param scrambled String a desencriptar
* @return String desencriptado
*/
public static String descramble(String scrambled)
{
if(scrambled == null)return null; // Si el String a desencriptar es null, no hago nada
byte [] SCRATCH = ("HTTPClient-tneilCPTTH").getBytes(); // Bytes utilizados en el Scramble de datos
String ret = "";
try
{
int tempSize = scrambled.length();
char [] tempData = scrambled.toCharArray();
for(int i = 0; i < tempData.length; i++)
{
if(tempData[i] == 36) tempSize --;
}
int scratch_size = SCRATCH.length;
for(int i = 0 ; i < tempData.length; i++)
{
char temp = tempData[i];
if(temp == 36)
{
temp = (char)(tempData[++i] - 37);
}
temp = (char)(temp ^ SCRATCH[(tempSize++) % scratch_size]);
ret += temp;
}
}catch(Exception malformedScrambledString){ malformedScrambledString.printStackTrace(); }
return ret;
}
//@gusbro\
// Constructors
/**
* Constructs a connection to the host from where the applet was loaded.
* Note that current security policies only let applets connect home.
*
* @param applet the current applet
*/
// public HTTPConnection(Object applet) throws ProtocolNotSuppException
// {
// if (SpecificImplementation.HTTPConnection != null)
// SpecificImplementation.HTTPConnection.createHttpConnectionFromApplet(applet, this);
// }
/**
* Constructs a connection to the specified host on port 80
*
* @param host the host
*/
public HTTPConnection(String host)
{
Setup(HTTP, host, 80, null, -1);
}
/**
* Constructs a connection to the specified host on the specified port
*
* @param host the host
* @param port the port
*/
public HTTPConnection(String host, int port)
{
Setup(HTTP, host, port, null, -1);
}
/**
* Constructs a connection to the specified host on the specified port,
* using the specified protocol (currently only "http" is supported).
*
* @param prot the protocol
* @param host the host
* @param port the port, or -1 for the default port
* @exception ProtocolNotSuppException if the protocol is not HTTP
*/
public HTTPConnection(String prot, String host, int port)
throws ProtocolNotSuppException
{
this(prot, host, port, null, -1);
}
/**
* Constructs a connection to the specified host on the specified port,
* using the specified protocol (currently only "http" is supported),
* local address, and local port.
*
* @param prot the protocol
* @param host the host
* @param port the port, or -1 for the default port
* @param localAddr the local address to bind to
* @param lcoalPort the local port to bind to
* @exception ProtocolNotSuppException if the protocol is not HTTP
*/
public HTTPConnection(String prot, String host, int port,
InetAddress localAddr, int localPort)
throws ProtocolNotSuppException
{
setInfo(prot, host, port, localAddr, localPort);
}
public void setInfo(String prot, String host, int port, InetAddress localAddr, int localPort) throws ProtocolNotSuppException
{
prot = prot.trim().toLowerCase();
if (!prot.equals("http") && !prot.equals("https"))
throw new ProtocolNotSuppException("Unsupported protocol '" + prot + "'");
if (prot.equals("http"))
Setup(HTTP, host, port, localAddr, localPort);
else if (prot.equals("https"))
Setup(HTTPS, host, port, localAddr, localPort);
else if (prot.equals("shttp"))
Setup(SHTTP, host, port, localAddr, localPort);
else if (prot.equals("http-ng"))
Setup(HTTP_NG, host, port, localAddr, localPort);
}
/**
* Constructs a connection to the host (port) as given in the url.
*
* @param url the url
* @exception ProtocolNotSuppException if the protocol is not HTTP
*/
public HTTPConnection(URL url) throws ProtocolNotSuppException
{
this(url.getProtocol(), url.getHost(), url.getPort());
}
/**
* Constructs a connection to the host (port) as given in the uri.
*
* @param uri the uri
* @exception ProtocolNotSuppException if the protocol is not HTTP
*/
public HTTPConnection(URI uri) throws ProtocolNotSuppException
{
this(uri.getScheme(), uri.getHost(), uri.getPort());
}
/**
* Sets the class variables. Must not be public.
*
* @param prot the protocol
* @param host the host
* @param port the port
* @param localAddr the local address to bind to; if null, it's ignored
* @param localPort the local port to bind to
*/
@SuppressWarnings("unchecked")
private void Setup(int prot, String host, int port, InetAddress localAddr,
int localPort)
{
Protocol = prot;
Host = host.trim().toLowerCase();
Port = port;
LocalAddr = localAddr;
LocalPort = localPort;
if (Port == -1)
Port = URI.defaultPort(getProtocol());
if (Default_Proxy_Host != null && !matchNonProxy(Host))
setCurrentProxy(Default_Proxy_Host, Default_Proxy_Port);
else
setCurrentProxy(null, 0);
Socks_client = Default_Socks_client;
Timeout = DefaultTimeout;
ModuleList = (Vector<Class<?>>) DefaultModuleList.clone();
allowUI = defaultAllowUI;
if (noKeepAlives)
setDefaultHeaders(new NVPair[] { new NVPair("Connection", "close") });
}
/**
* Determines if the given host matches any entry in the non-proxy list.
*
* @param host the host to match - must be trim()'d and lowercase
* @return true if a match is found, false otherwise
* @see #dontProxyFor(java.lang.String)
*/
private boolean matchNonProxy(String host)
{
// Check host name list
if (non_proxy_host_list.get(host) != null)
return true;
// Check domain name list
for (int idx=0; idx<non_proxy_dom_list.size(); idx++)
if (host.endsWith(non_proxy_dom_list.elementAt(idx)))
return true;
// Check IP-address and subnet list
if (non_proxy_addr_list.size() == 0)
return false;
InetAddress[] host_addr;
try
{ host_addr = InetAddress.getAllByName(host); }
catch (UnknownHostException uhe)
{ return false; } // maybe the proxy has better luck
for (int idx=0; idx<non_proxy_addr_list.size(); idx++)
{
byte[] addr = non_proxy_addr_list.elementAt(idx);
byte[] mask = non_proxy_mask_list.elementAt(idx);
ip_loop: for (int idx2=0; idx2<host_addr.length; idx2++)
{
byte[] raw_addr = host_addr[idx2].getAddress();
if (raw_addr.length != addr.length) continue;
for (int idx3=0; idx3<raw_addr.length; idx3++)
{
if ((raw_addr[idx3] & mask[idx3]) != (addr[idx3] & mask[idx3]))
continue ip_loop;
}
return true;
}
}
return false;
}
// Methods
/**
* Sends the HEAD request. This request is just like the corresponding
* GET except that it only returns the headers and no data.
*
* @see #Get(java.lang.String)
* @param file the absolute path of the file
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Head(String file) throws IOException, ModuleException
{
return Head(file, (String) null, null);
}
/**
* Sends the HEAD request. This request is just like the corresponding
* GET except that it only returns the headers and no data.
*
* @see #Get(java.lang.String, HTTPClient.NVPair[])
* @param file the absolute path of the file
* @param form_data an array of Name/Value pairs
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Head(String file, NVPair form_data[])
throws IOException, ModuleException
{
return Head(file, form_data, null);
}
/**
* Sends the HEAD request. This request is just like the corresponding
* GET except that it only returns the headers and no data.
*
* @see #Get(java.lang.String, HTTPClient.NVPair[], HTTPClient.NVPair[])
* @param file the absolute path of the file
* @param form_data an array of Name/Value pairs
* @param headers additional headers
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Head(String file, NVPair[] form_data, NVPair[] headers)
throws IOException, ModuleException
{
String File = stripRef(file),
query = Codecs.nv2query(form_data);
if (query != null && query.length() > 0)
File += "?" + query;
return setupRequest("HEAD", File, headers, null, null);
}
/**
* Sends the HEAD request. This request is just like the corresponding
* GET except that it only returns the headers and no data.
*
* @see #Get(java.lang.String, java.lang.String)
* @param file the absolute path of the file
* @param query the query string; it will be urlencoded
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Head(String file, String query)
throws IOException, ModuleException
{
return Head(file, query, null);
}
/**
* Sends the HEAD request. This request is just like the corresponding
* GET except that it only returns the headers and no data.
*
* @see #Get(java.lang.String, java.lang.String, HTTPClient.NVPair[])
* @param file the absolute path of the file
* @param query the query string; it will be urlencoded
* @param headers additional headers
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Head(String file, String query, NVPair[] headers)
throws IOException, ModuleException
{
String File = stripRef(file);
if (query != null && query.length() > 0)
File += "?" + Codecs.URLEncode(query);
return setupRequest("HEAD", File, headers, null, null);
}
/**
* GETs the file.
*
* @param file the absolute path of the file
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Get(String file) throws IOException, ModuleException
{
return Get(file, (String) null, null);
}
/**
* GETs the file with a query consisting of the specified form-data.
* The data is urlencoded, turned into a string of the form
* "name1=value1&name2=value2" and then sent as a query string.
*
* @param file the absolute path of the file
* @param form_data an array of Name/Value pairs
* @return an HTTPResponse structure containing the response
* @exception java.io.IOException when an exception is returned from
* the socket.
* @exception ModuleException if an exception is encountered in any module.
*/
public HTTPResponse Get(String file, NVPair form_data[])
throws IOException, ModuleException
{
return Get(file, form_data, null);
}
/**
* GETs the file with a query consisting of the specified form-data.
* The data is urlencoded, turned into a string of the form
* "name1=value1&name2=value2" and then sent as a query string.
*
* @param file the absolute path of the file
* @param form_data an array of Name/Value pairs
* @param headers additional headers