-
Notifications
You must be signed in to change notification settings - Fork 118
/
HttpRequest.java
3259 lines (2938 loc) · 86.4 KB
/
HttpRequest.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
/*
* Copyright (c) 2014 Kevin Sawicki <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
package com.github.kevinsawicki.http;
import static java.net.HttpURLConnection.HTTP_BAD_REQUEST;
import static java.net.HttpURLConnection.HTTP_CREATED;
import static java.net.HttpURLConnection.HTTP_INTERNAL_ERROR;
import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
import static java.net.HttpURLConnection.HTTP_NOT_FOUND;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.net.HttpURLConnection.HTTP_OK;
import static java.net.Proxy.Type.HTTP;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.Flushable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.security.AccessController;
import java.security.GeneralSecurityException;
import java.security.PrivilegedAction;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* A fluid interface for making HTTP requests using an underlying
* {@link HttpURLConnection} (or sub-class).
* <p>
* Each instance supports making a single request and cannot be reused for
* further requests.
*/
public class HttpRequest {
/**
* 'UTF-8' charset name
*/
public static final String CHARSET_UTF8 = "UTF-8";
/**
* 'application/x-www-form-urlencoded' content type header value
*/
public static final String CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
/**
* 'application/json' content type header value
*/
public static final String CONTENT_TYPE_JSON = "application/json";
/**
* 'gzip' encoding header value
*/
public static final String ENCODING_GZIP = "gzip";
/**
* 'Accept' header name
*/
public static final String HEADER_ACCEPT = "Accept";
/**
* 'Accept-Charset' header name
*/
public static final String HEADER_ACCEPT_CHARSET = "Accept-Charset";
/**
* 'Accept-Encoding' header name
*/
public static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding";
/**
* 'Authorization' header name
*/
public static final String HEADER_AUTHORIZATION = "Authorization";
/**
* 'Cache-Control' header name
*/
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
/**
* 'Content-Encoding' header name
*/
public static final String HEADER_CONTENT_ENCODING = "Content-Encoding";
/**
* 'Content-Length' header name
*/
public static final String HEADER_CONTENT_LENGTH = "Content-Length";
/**
* 'Content-Type' header name
*/
public static final String HEADER_CONTENT_TYPE = "Content-Type";
/**
* 'Date' header name
*/
public static final String HEADER_DATE = "Date";
/**
* 'ETag' header name
*/
public static final String HEADER_ETAG = "ETag";
/**
* 'Expires' header name
*/
public static final String HEADER_EXPIRES = "Expires";
/**
* 'If-None-Match' header name
*/
public static final String HEADER_IF_NONE_MATCH = "If-None-Match";
/**
* 'Last-Modified' header name
*/
public static final String HEADER_LAST_MODIFIED = "Last-Modified";
/**
* 'Location' header name
*/
public static final String HEADER_LOCATION = "Location";
/**
* 'Proxy-Authorization' header name
*/
public static final String HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization";
/**
* 'Referer' header name
*/
public static final String HEADER_REFERER = "Referer";
/**
* 'Server' header name
*/
public static final String HEADER_SERVER = "Server";
/**
* 'User-Agent' header name
*/
public static final String HEADER_USER_AGENT = "User-Agent";
/**
* 'DELETE' request method
*/
public static final String METHOD_DELETE = "DELETE";
/**
* 'GET' request method
*/
public static final String METHOD_GET = "GET";
/**
* 'HEAD' request method
*/
public static final String METHOD_HEAD = "HEAD";
/**
* 'OPTIONS' options method
*/
public static final String METHOD_OPTIONS = "OPTIONS";
/**
* 'POST' request method
*/
public static final String METHOD_POST = "POST";
/**
* 'PUT' request method
*/
public static final String METHOD_PUT = "PUT";
/**
* 'TRACE' request method
*/
public static final String METHOD_TRACE = "TRACE";
/**
* 'charset' header value parameter
*/
public static final String PARAM_CHARSET = "charset";
private static final String BOUNDARY = "00content0boundary00";
private static final String CONTENT_TYPE_MULTIPART = "multipart/form-data; boundary="
+ BOUNDARY;
private static final String CRLF = "\r\n";
private static final String[] EMPTY_STRINGS = new String[0];
private static SSLSocketFactory TRUSTED_FACTORY;
private static HostnameVerifier TRUSTED_VERIFIER;
private static String getValidCharset(final String charset) {
if (charset != null && charset.length() > 0)
return charset;
else
return CHARSET_UTF8;
}
private static SSLSocketFactory getTrustedFactory()
throws HttpRequestException {
if (TRUSTED_FACTORY == null) {
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
// Intentionally left blank
}
} };
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, trustAllCerts, new SecureRandom());
TRUSTED_FACTORY = context.getSocketFactory();
} catch (GeneralSecurityException e) {
IOException ioException = new IOException(
"Security exception configuring SSL context");
ioException.initCause(e);
throw new HttpRequestException(ioException);
}
}
return TRUSTED_FACTORY;
}
private static HostnameVerifier getTrustedVerifier() {
if (TRUSTED_VERIFIER == null)
TRUSTED_VERIFIER = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
return TRUSTED_VERIFIER;
}
private static StringBuilder addPathSeparator(final String baseUrl,
final StringBuilder result) {
// Add trailing slash if the base URL doesn't have any path segments.
//
// The following test is checking for the last slash not being part of
// the protocol to host separator: '://'.
if (baseUrl.indexOf(':') + 2 == baseUrl.lastIndexOf('/'))
result.append('/');
return result;
}
private static StringBuilder addParamPrefix(final String baseUrl,
final StringBuilder result) {
// Add '?' if missing and add '&' if params already exist in base url
final int queryStart = baseUrl.indexOf('?');
final int lastChar = result.length() - 1;
if (queryStart == -1)
result.append('?');
else if (queryStart < lastChar && baseUrl.charAt(lastChar) != '&')
result.append('&');
return result;
}
private static StringBuilder addParam(final Object key, Object value,
final StringBuilder result) {
if (value != null && value.getClass().isArray())
value = arrayToList(value);
if (value instanceof Iterable<?>) {
Iterator<?> iterator = ((Iterable<?>) value).iterator();
while (iterator.hasNext()) {
result.append(key);
result.append("[]=");
Object element = iterator.next();
if (element != null)
result.append(element);
if (iterator.hasNext())
result.append("&");
}
} else {
result.append(key);
result.append("=");
if (value != null)
result.append(value);
}
return result;
}
/**
* Creates {@link HttpURLConnection HTTP connections} for
* {@link URL urls}.
*/
public interface ConnectionFactory {
/**
* Open an {@link HttpURLConnection} for the specified {@link URL}.
*
* @throws IOException
*/
HttpURLConnection create(URL url) throws IOException;
/**
* Open an {@link HttpURLConnection} for the specified {@link URL}
* and {@link Proxy}.
*
* @throws IOException
*/
HttpURLConnection create(URL url, Proxy proxy) throws IOException;
/**
* A {@link ConnectionFactory} which uses the built-in
* {@link URL#openConnection()}
*/
ConnectionFactory DEFAULT = new ConnectionFactory() {
public HttpURLConnection create(URL url) throws IOException {
return (HttpURLConnection) url.openConnection();
}
public HttpURLConnection create(URL url, Proxy proxy) throws IOException {
return (HttpURLConnection) url.openConnection(proxy);
}
};
}
private static ConnectionFactory CONNECTION_FACTORY = ConnectionFactory.DEFAULT;
/**
* Specify the {@link ConnectionFactory} used to create new requests.
*/
public static void setConnectionFactory(final ConnectionFactory connectionFactory) {
if (connectionFactory == null)
CONNECTION_FACTORY = ConnectionFactory.DEFAULT;
else
CONNECTION_FACTORY = connectionFactory;
}
/**
* Callback interface for reporting upload progress for a request.
*/
public interface UploadProgress {
/**
* Callback invoked as data is uploaded by the request.
*
* @param uploaded The number of bytes already uploaded
* @param total The total number of bytes that will be uploaded or -1 if
* the length is unknown.
*/
void onUpload(long uploaded, long total);
UploadProgress DEFAULT = new UploadProgress() {
public void onUpload(long uploaded, long total) {
}
};
}
/**
* <p>
* Encodes and decodes to and from Base64 notation.
* </p>
* <p>
* I am placing this code in the Public Domain. Do with it as you will. This
* software comes with no guarantees or warranties but with plenty of
* well-wishing instead! Please visit <a
* href="http://iharder.net/base64">http://iharder.net/base64</a> periodically
* to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author [email protected]
* @version 2.3.7
*/
public static class Base64 {
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "US-ASCII";
/** The 64 valid Base64 values. */
private final static byte[] _STANDARD_ALPHABET = { (byte) 'A', (byte) 'B',
(byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H',
(byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',
(byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T',
(byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f',
(byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l',
(byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r',
(byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x',
(byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',
(byte) '+', (byte) '/' };
/** Defeats instantiation. */
private Base64() {
}
/**
* <p>
* Encodes up to three bytes of the array <var>source</var> and writes the
* resulting four Base64 bytes to <var>destination</var>. The source and
* destination arrays can be manipulated anywhere along their length by
* specifying <var>srcOffset</var> and <var>destOffset</var>. This method
* does not check to make sure your arrays are large enough to accomodate
* <var>srcOffset</var> + 3 for the <var>source</var> array or
* <var>destOffset</var> + 4 for the <var>destination</var> array. The
* actual number of significant bytes in your array is given by
* <var>numSigBytes</var>.
* </p>
* <p>
* This is the lowest level of the encoding methods with all possible
* parameters.
* </p>
*
* @param source
* the array to convert
* @param srcOffset
* the index where conversion begins
* @param numSigBytes
* the number of significant bytes in your array
* @param destination
* the array to hold the conversion
* @param destOffset
* the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset) {
byte[] ALPHABET = _STANDARD_ALPHABET;
int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = ALPHABET[(inBuff >>> 18)];
destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
}
}
/**
* Encode string as a byte array in Base64 annotation.
*
* @param string
* @return The Base64-encoded data as a string
*/
public static String encode(String string) {
byte[] bytes;
try {
bytes = string.getBytes(PREFERRED_ENCODING);
} catch (UnsupportedEncodingException e) {
bytes = string.getBytes();
}
return encodeBytes(bytes);
}
/**
* Encodes a byte array into Base64 notation.
*
* @param source
* The data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes(byte[] source) {
return encodeBytes(source, 0, source.length);
}
/**
* Encodes a byte array into Base64 notation.
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @return The Base64-encoded data as a String
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.0
*/
public static String encodeBytes(byte[] source, int off, int len) {
byte[] encoded = encodeBytesToBytes(source, off, len);
try {
return new String(encoded, PREFERRED_ENCODING);
} catch (UnsupportedEncodingException uue) {
return new String(encoded);
}
}
/**
* Similar to {@link #encodeBytes(byte[], int, int)} but returns a byte
* array instead of instantiating a String. This is more efficient if you're
* working with I/O streams and have large data sets to encode.
*
*
* @param source
* The data to convert
* @param off
* Offset in array where conversion should begin
* @param len
* Length of data to convert
* @return The Base64-encoded data as a String if there is an error
* @throws NullPointerException
* if source array is null
* @throws IllegalArgumentException
* if source array, offset, or length are invalid
* @since 2.3.1
*/
public static byte[] encodeBytesToBytes(byte[] source, int off, int len) {
if (source == null)
throw new NullPointerException("Cannot serialize a null array.");
if (off < 0)
throw new IllegalArgumentException("Cannot have negative offset: "
+ off);
if (len < 0)
throw new IllegalArgumentException("Cannot have length offset: " + len);
if (off + len > source.length)
throw new IllegalArgumentException(
String
.format(
"Cannot have offset of %d and length of %d with array of length %d",
off, len, source.length));
// Bytes needed for actual encoding
int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0);
byte[] outBuff = new byte[encLen];
int d = 0;
int e = 0;
int len2 = len - 2;
for (; d < len2; d += 3, e += 4)
encode3to4(source, d + off, 3, outBuff, e);
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e);
e += 4;
}
if (e <= outBuff.length - 1) {
byte[] finalOut = new byte[e];
System.arraycopy(outBuff, 0, finalOut, 0, e);
return finalOut;
} else
return outBuff;
}
}
/**
* HTTP request exception whose cause is always an {@link IOException}
*/
public static class HttpRequestException extends RuntimeException {
private static final long serialVersionUID = -1170466989781746231L;
/**
* Create a new HttpRequestException with the given cause
*
* @param cause
*/
public HttpRequestException(final IOException cause) {
super(cause);
}
/**
* Get {@link IOException} that triggered this request exception
*
* @return {@link IOException} cause
*/
@Override
public IOException getCause() {
return (IOException) super.getCause();
}
}
/**
* Operation that handles executing a callback once complete and handling
* nested exceptions
*
* @param <V>
*/
protected static abstract class Operation<V> implements Callable<V> {
/**
* Run operation
*
* @return result
* @throws HttpRequestException
* @throws IOException
*/
protected abstract V run() throws HttpRequestException, IOException;
/**
* Operation complete callback
*
* @throws IOException
*/
protected abstract void done() throws IOException;
public V call() throws HttpRequestException {
boolean thrown = false;
try {
return run();
} catch (HttpRequestException e) {
thrown = true;
throw e;
} catch (IOException e) {
thrown = true;
throw new HttpRequestException(e);
} finally {
try {
done();
} catch (IOException e) {
if (!thrown)
throw new HttpRequestException(e);
}
}
}
}
/**
* Class that ensures a {@link Closeable} gets closed with proper exception
* handling.
*
* @param <V>
*/
protected static abstract class CloseOperation<V> extends Operation<V> {
private final Closeable closeable;
private final boolean ignoreCloseExceptions;
/**
* Create closer for operation
*
* @param closeable
* @param ignoreCloseExceptions
*/
protected CloseOperation(final Closeable closeable,
final boolean ignoreCloseExceptions) {
this.closeable = closeable;
this.ignoreCloseExceptions = ignoreCloseExceptions;
}
@Override
protected void done() throws IOException {
if (closeable instanceof Flushable)
((Flushable) closeable).flush();
if (ignoreCloseExceptions)
try {
closeable.close();
} catch (IOException e) {
// Ignored
}
else
closeable.close();
}
}
/**
* Class that and ensures a {@link Flushable} gets flushed with proper
* exception handling.
*
* @param <V>
*/
protected static abstract class FlushOperation<V> extends Operation<V> {
private final Flushable flushable;
/**
* Create flush operation
*
* @param flushable
*/
protected FlushOperation(final Flushable flushable) {
this.flushable = flushable;
}
@Override
protected void done() throws IOException {
flushable.flush();
}
}
/**
* Request output stream
*/
public static class RequestOutputStream extends BufferedOutputStream {
private final CharsetEncoder encoder;
/**
* Create request output stream
*
* @param stream
* @param charset
* @param bufferSize
*/
public RequestOutputStream(final OutputStream stream, final String charset,
final int bufferSize) {
super(stream, bufferSize);
encoder = Charset.forName(getValidCharset(charset)).newEncoder();
}
/**
* Write string to stream
*
* @param value
* @return this stream
* @throws IOException
*/
public RequestOutputStream write(final String value) throws IOException {
final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value));
super.write(bytes.array(), 0, bytes.limit());
return this;
}
}
/**
* Represents array of any type as list of objects so we can easily iterate over it
* @param array of elements
* @return list with the same elements
*/
private static List<Object> arrayToList(final Object array) {
if (array instanceof Object[])
return Arrays.asList((Object[]) array);
List<Object> result = new ArrayList<Object>();
// Arrays of the primitive types can't be cast to array of Object, so this:
if (array instanceof int[])
for (int value : (int[]) array) result.add(value);
else if (array instanceof boolean[])
for (boolean value : (boolean[]) array) result.add(value);
else if (array instanceof long[])
for (long value : (long[]) array) result.add(value);
else if (array instanceof float[])
for (float value : (float[]) array) result.add(value);
else if (array instanceof double[])
for (double value : (double[]) array) result.add(value);
else if (array instanceof short[])
for (short value : (short[]) array) result.add(value);
else if (array instanceof byte[])
for (byte value : (byte[]) array) result.add(value);
else if (array instanceof char[])
for (char value : (char[]) array) result.add(value);
return result;
}
/**
* Encode the given URL as an ASCII {@link String}
* <p>
* This method ensures the path and query segments of the URL are properly
* encoded such as ' ' characters being encoded to '%20' or any UTF-8
* characters that are non-ASCII. No encoding of URLs is done by default by
* the {@link HttpRequest} constructors and so if URL encoding is needed this
* method should be called before calling the {@link HttpRequest} constructor.
*
* @param url
* @return encoded URL
* @throws HttpRequestException
*/
public static String encode(final CharSequence url)
throws HttpRequestException {
URL parsed;
try {
parsed = new URL(url.toString());
} catch (IOException e) {
throw new HttpRequestException(e);
}
String host = parsed.getHost();
int port = parsed.getPort();
if (port != -1)
host = host + ':' + Integer.toString(port);
try {
String encoded = new URI(parsed.getProtocol(), host, parsed.getPath(),
parsed.getQuery(), null).toASCIIString();
int paramsStart = encoded.indexOf('?');
if (paramsStart > 0 && paramsStart + 1 < encoded.length())
encoded = encoded.substring(0, paramsStart + 1)
+ encoded.substring(paramsStart + 1).replace("+", "%2B");
return encoded;
} catch (URISyntaxException e) {
IOException io = new IOException("Parsing URI failed");
io.initCause(e);
throw new HttpRequestException(io);
}
}
/**
* Append given map as query parameters to the base URL
* <p>
* Each map entry's key will be a parameter name and the value's
* {@link Object#toString()} will be the parameter value.
*
* @param url
* @param params
* @return URL with appended query params
*/
public static String append(final CharSequence url, final Map<?, ?> params) {
final String baseUrl = url.toString();
if (params == null || params.isEmpty())
return baseUrl;
final StringBuilder result = new StringBuilder(baseUrl);
addPathSeparator(baseUrl, result);
addParamPrefix(baseUrl, result);
Entry<?, ?> entry;
Iterator<?> iterator = params.entrySet().iterator();
entry = (Entry<?, ?>) iterator.next();
addParam(entry.getKey().toString(), entry.getValue(), result);
while (iterator.hasNext()) {
result.append('&');
entry = (Entry<?, ?>) iterator.next();
addParam(entry.getKey().toString(), entry.getValue(), result);
}
return result.toString();
}
/**
* Append given name/value pairs as query parameters to the base URL
* <p>
* The params argument is interpreted as a sequence of name/value pairs so the
* given number of params must be divisible by 2.
*
* @param url
* @param params
* name/value pairs
* @return URL with appended query params
*/
public static String append(final CharSequence url, final Object... params) {
final String baseUrl = url.toString();
if (params == null || params.length == 0)
return baseUrl;
if (params.length % 2 != 0)
throw new IllegalArgumentException(
"Must specify an even number of parameter names/values");
final StringBuilder result = new StringBuilder(baseUrl);
addPathSeparator(baseUrl, result);
addParamPrefix(baseUrl, result);
addParam(params[0], params[1], result);
for (int i = 2; i < params.length; i += 2) {
result.append('&');
addParam(params[i], params[i + 1], result);
}
return result.toString();
}
/**
* Start a 'GET' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest get(final CharSequence url)
throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
/**
* Start a 'GET' request to the given URL
*
* @param url
* @return request
* @throws HttpRequestException
*/
public static HttpRequest get(final URL url) throws HttpRequestException {
return new HttpRequest(url, METHOD_GET);
}
/**
* Start a 'GET' request to the given URL along with the query params
*
* @param baseUrl
* @param params
* The query parameters to include as part of the baseUrl
* @param encode