forked from kgilmer/touge
/
RestClient.java
1551 lines (1332 loc) · 43.7 KB
/
RestClient.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
/*
* This file is in the public domain, furnished "as is", without technical
* support, and with no warranty, express or implied, as to its usefulness for
* any purpose.
*/
package org.touge.restclient;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
/**
* A client library for accessing resources via HTTP.
*
* @author kgilmer
*
*/
public class RestClient {
private static final String HEADER_CONTENT_TYPE = "Content-Type";
private static final String APPLICATION_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
private static final int COPY_BUFFER_SIZE = 1024 * 4;
private static final int RANDOM_CHAR_COUNT = 15;
private static final String HEADER_TYPE = HEADER_CONTENT_TYPE;
private static final String HEADER_PARA = "Content-Disposition: form-data";
private static final String MULTIPART_FORM_DATA_CONTENT_TYPE = "multipart/form-data";
private static final String FILE_NAME = "filename";
private static final String LINE_ENDING = "\r\n";
private static final String BOUNDARY = "boundary=";
private static final String PARA_NAME = "name";
/**
* HTTP methods supported by REST client.
*
*/
public enum HttpMethod {
GET, POST, PUT, DELETE, HEAD
}
/**
* implement to provide an HttpURLConnection w/ some properties pre-set see
* BasicAuthenticationConnectionProvider for an example.
*
* This is passed into HttpRequest on creation to provide it w/ the connection
*
* @author bballantine
*
*/
public interface ConnectionProvider {
/**
* @param urlStr url that is used to source the connection
* @return an appropriate instance of HttpURLConnection
* @throws IOException on I/O error.
*/
HttpURLConnection getConnection(String urlStr) throws IOException;
}
/**
* Implementors can configure the http connection before every call is made.
* Useful for setting headers that always need to be present in every WS
* call to a given server.
*
*/
public interface ConnectionInitializer {
/**
* @param connection
* HttpURLConnection
*/
void initialize(HttpURLConnection connection);
}
/**
* Utility interface for building URLs from String segments.
*/
public interface URLBuilder extends Cloneable {
/**
* Append a segment to the URL. Will handle leading and trailing slashes, and schemes.
*
* @param segment to be appended
* @return instance of builder
*/
URLBuilder append(String ... segment);
/**
* @param value if true, scheme is set to https, otherwise http.
* @return instance of builder
*/
URLBuilder setHttps(boolean value);
/**
* @return URL as a String with scheme
*/
@Override
String toString();
/**
* @return A new instance of URLBuilder with same path and scheme as parent.
*/
URLBuilder copy();
/**
* @param segments new segment to append to new copy of URLBuilder
* @return A new instance of URLBuilder with same path and scheme as parent, with segment appended.
*/
URLBuilder copy(String ... segments);
/**
* Add a query string parameter to the URL.
*
* @param key key name. Same key name can be used multiple times.
* @param value value of parameter.
* @return URLBuilder
*/
URLBuilder addParameter(String key, String value);
/**
*
* @param value if true, scheme will be present in toString(), otherwise will be omitted.
* @return URLBuilder
*/
URLBuilder emitScheme(boolean value);
/**
* @param value if true, domain is emitted in toString(), false means it will not be emitted.
* @return URLBuilder
*/
URLBuilder emitDomain(boolean value);
}
/**
*
*
* @param <T>
*/
public interface ResponseDeserializer<T> {
/**
* Deserialize the input.
* @param input input stream of response
* @param responseCode HTTP response from server
* @param headers HTTP response headers
* @return deserialized representation of response
* @throws IOException on I/O error
*/
T deserialize(InputStream input, int responseCode, Map<String, List<String>> headers) throws IOException;
}
/**
* A HTTPResponseDeserializer that returns the entire response as a String.
*/
public static final ResponseDeserializer<String> STRING_DESERIALIZER = new ResponseDeserializer<String>() {
@Override
public String deserialize(InputStream input, int responseCode, Map<String,
List<String>> headers) throws IOException {
if (input != null)
return new String(readStream(input));
return null;
}
};
/**
* A HTTPResponseDeserializer that returns true if the response from the server was not an error.
*/
public static final ResponseDeserializer<Integer> HTTP_CODE_DESERIALIZER = new ResponseDeserializer<Integer>() {
@Override
public Integer deserialize(InputStream input, int responseCode, Map<String,
List<String>> headers) throws IOException {
return responseCode;
}
};
/**
* A HTTPResponseDeserializer that simply returns the internal inputstream.
* Useful for clients that wish to handle the response input stream manually.
*/
public static final ResponseDeserializer<InputStream> INPUTSTREAM_DESERIALIZER = new ResponseDeserializer<InputStream>() {
@Override
public InputStream deserialize(InputStream input, int responseCode, Map<String,
List<String>> headers) throws IOException {
return input;
}
};
/**
*
*/
public static final ErrorHandler THROW_ALL_ERRORS = new ErrorHandler() {
@Override
public void handleError(int code, String message) throws IOException {
if (code > 0)
throw new IOException("HTTP Error " + code + " was returned from the server: " + message);
else
throw new IOException("A non-HTTP error was returned from the server.");
}
};
/**
*
*/
public static final ErrorHandler THROW_5XX_ERRORS = new ErrorHandler() {
@Override
public void handleError(int code, String message) throws IOException {
if (code > 499 && code < 600)
throw new IOException("HTTP Error " + code + " was returned from the server: " + message);
}
};
/**
* Time format for debug messages.
*/
private static final String DEBUG_TIME_FORMAT = "H:mm:ss:SSS";
/**
* The response from the server for a given request.
*
* @param <T>
*/
public interface Response<T> {
/**
* Cancel the request.
*
* @param mayInterruptIfRunning
* @return
*/
public abstract boolean cancel(boolean mayInterruptIfRunning);
/**
* @return true if the request has been canceled
*/
public abstract boolean isCancelled();
/**
* @return true if the request has been completed
*/
public abstract boolean isDone();
/**
* @return the content (body) of the response.
*
* @throws IOException
*/
public abstract T getContent() throws IOException;
/**
* @return The HttpURLConnection associated with the request.
*/
HttpURLConnection getConnection();
/**
* @return The HTTP method that was used in the call.
*/
HttpMethod getRequestMethod();
/**
* @return The URL that was used in the call.
*/
String getRequestUrl();
/**
* @return The HTTP Response code from the server.
* @throws IOException on I/O error.
*/
int getCode() throws IOException;
/**
* @return true if error code or an exception is raised, false otherwise.
*/
boolean isError();
/**
* @return error message or null if failure to get message from server.
*/
public abstract String getErrorMessage();
}
/**
* The ErrorHander does something based on an HTTP or I/O error.
*
*/
public interface ErrorHandler {
/**
* @param code the HTTP code of the error
* @param human-readable error message
* @throws IOException on I/O error
*/
void handleError(int code, String message) throws IOException;
}
/**
* Used to specify a file to upload in a multipart POST.
*
*/
public static class FormFile extends File {
private static final long serialVersionUID = 2957338960806476533L;
private final String mimeType;
/**
* @param pathname
*/
public FormFile(String pathname, String mimeType) {
super(pathname);
this.mimeType = mimeType;
}
/**
* @return Mime type of file.
*/
public String getMimeType() {
return mimeType;
}
}
/**
* Used to specify a file to upload in a multipart POST.
*
*/
public static class FormInputStream extends InputStream {
private static final long serialVersionUID = 2957338960806476533L;
private final String mimeType;
private final InputStream parent;
private final String name;
/**
* @param parent Input stream of file
* @param name name of file
* @param mimeType mimetype for content of file
*/
public FormInputStream(InputStream parent, String name, String mimeType) {
this.parent = parent;
this.name = name;
this.mimeType = mimeType;
}
/**
* @return Mime type of file.
*/
public String getMimeType() {
return mimeType;
}
@Override
public int read() throws IOException {
return parent.read();
}
@Override
public int read(byte[] b) throws IOException {
return parent.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return parent.read(b, off, len);
}
/**
* @return name of content
*/
public String getName() {
return name;
}
}
/**
* A Connection Initializer that sends Basic Authentication header in the request.
*
*/
public static class BasicAuthConnectionInitializer implements ConnectionInitializer {
private final String field;
/**
* @param username
* @param password
*/
public BasicAuthConnectionInitializer(String username, String password) {
String userpass = username + ":" + password;
field = "Basic " + Base64.encodeBytes(userpass.getBytes());
}
@Override
public void initialize(HttpURLConnection connection) {
connection.addRequestProperty("Authorization", field);
}
}
private static Random RNG;
private ConnectionProvider connectionProvider;
private final List<ConnectionInitializer> connectionInitializers;
private ErrorHandler errorHandler;
private PrintWriter debugStream;
//private StringBuilder debugBuffer;
private SimpleDateFormat debugTimeFormat;
/**
* Default constructor.
*/
public RestClient() {
this.connectionProvider = new DefaultConnectionProvider();
this.connectionInitializers = new ArrayList<ConnectionInitializer>();
this.errorHandler = null;
}
/**
* @param connectionProvider ConnectionProvider
*/
public RestClient(ConnectionProvider connectionProvider) {
this.connectionProvider = connectionProvider;
this.connectionInitializers = new ArrayList<ConnectionInitializer>();
this.errorHandler = null;
}
/**
* @param initializer ConnectionInitializer
*/
public RestClient(ConnectionInitializer initializer) {
this();
connectionInitializers.add(initializer);
}
/**
* Creates a ReSTClient with basic authentication credentials.
* @param username
* @param password
*/
public RestClient(String username, String password) {
this();
connectionInitializers.add(new BasicAuthConnectionInitializer(username, password));
}
/**
* @param connectionProvider ConnectionProvider
* @param initializer ConnectionInitializer
*/
public RestClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer) {
this(connectionProvider);
connectionInitializers.add(initializer);
}
/**
* @param initializer ConnectionInitializer
* @param deserializer ResponseDeserializer<T>
*/
public RestClient(ConnectionInitializer initializer, ResponseDeserializer<?> deserializer) {
this(initializer);
}
/**
* @param connectionProvider ConnectionProvider
* @param initializer ConnectionInitializer
* @param deserializer ResponseDeserializer<T>
*/
public RestClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer, ResponseDeserializer<?> deserializer) {
this(connectionProvider, initializer);
}
/**
* @param connectionProvider ConnectionProvider
* @param initializer ConnectionInitializer
* @param deserializer ResponseDeserializer<T>
* @param errorHandler ErrorHandler
*/
public RestClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer,
ResponseDeserializer<?> deserializer, ErrorHandler errorHandler) {
this.connectionProvider = connectionProvider;
this.connectionInitializers = new ArrayList<ConnectionInitializer>();
this.errorHandler = errorHandler;
connectionInitializers.add(initializer);
}
/**
* @param connectionProvider ConnectionProvider
* @param initializer ConnectionInitializer
* @param deserializer ResponseDeserializer<T>
* @param errorHandler ErrorHandler
* @param debugStream OutputStream to pass debug messages to. If null, no debug output.
*/
public RestClient(ConnectionProvider connectionProvider, ConnectionInitializer initializer,
ResponseDeserializer<?> deserializer, ErrorHandler errorHandler, PrintWriter debugStream) {
this.connectionProvider = connectionProvider;
this.connectionInitializers = new ArrayList<ConnectionInitializer>();
this.errorHandler = errorHandler;
this.debugStream = debugStream;
connectionInitializers.add(initializer);
}
// Public methods
/**
* @return ErrorHandler
*/
public ErrorHandler getErrorHandler() {
return errorHandler;
}
/**
* Sets an error handler for the client. If no error handler is set, HTTP (application level) errors will be ignored
* by the client.
*
* Creating a custom ErrorHandler let's the client handle specific errors from the server in an application specific way.
*
* See also: THROW_ALL_ERRORS, THROW_5XX_ERRORS
*
* @param handler ErrorHandler
*/
public void setErrorHandler(ErrorHandler handler) {
this.errorHandler = handler;
}
/**
* Sets a debug OutputStream for the client. If null is passed, no debug output
* will be generated.
*
* @param debugStream OutputStream
*/
public void setDebugWriter(PrintWriter writer) {
this.debugStream = writer;
if (writer != null && debugTimeFormat == null) {
debugTimeFormat = new SimpleDateFormat(DEBUG_TIME_FORMAT);
}
}
/**
* @param provider ConnectionProvider
*/
public void setConnectionProvider(ConnectionProvider provider) {
this.connectionProvider = provider;
}
/**
* @return ConnectionProvider
*/
public ConnectionProvider getConnectionProvider() {
return connectionProvider;
}
/**
* @param initializer
*/
public ConnectionInitializer addConnectionInitializer(ConnectionInitializer initializer) {
if (!connectionInitializers.contains(initializer))
connectionInitializers.add(initializer);
return initializer;
}
/**
* @param initializer ConnectionInitializer
* @return ConnectionInitializer
*/
public boolean removeConnectionInitializer(ConnectionInitializer initializer) {
return connectionInitializers.remove(initializer);
}
/**
* This is the primary call in RestClient. All other HTTP method calls call this method with some specific parameters.
* For flexibility this method is exposed to clients but should not be used in a majority of cases. See callGet(),
* callPost() etc. for the simplest usage. This call is asynchronous, the Response works like a Future.
*
* This method handles errors based on how the client is configured. If no Deserializer or ErrorHander is specified
* the response content will produce null. The response class will contain the HTTP error information.
*
* @param method HTTP method. Cannot be null.
* @param url url of server. Cannot be null.
* @param deserializer class to deserialize the response body. If null then response is deserialized to a String.
* @param content Optional content to pass to server, can be null.
* @param headers HTTP headers that should be appended to the call. These are in addition to any headers set
* in any ConnectionInitializers associated with client.
* @param <T> type to deserialize to
* @return deserialized response
* @throws IOException on I/O error
*/
public <T> Response<T> call(final HttpMethod method, final String url, final ResponseDeserializer<T> deserializer,
InputStream content, Map<String, String> headers) throws IOException {
validateArguments(method, url);
String httpUrl = url;
if (!url.toLowerCase().startsWith("http://"))
httpUrl = "http://" + url;
StringBuilder debugBuffer = null;
if (debugStream != null)
debugBuffer = debugStart(httpUrl, method.toString());
final HttpURLConnection connection = connectionProvider.getConnection(httpUrl);
connection.setRequestMethod(method.toString());
for (ConnectionInitializer initializer : connectionInitializers)
initializer.initialize(connection);
if (headers != null && headers.size() > 0)
for (Map.Entry<String, String> entry : headers.entrySet())
connection.addRequestProperty(entry.getKey(), entry.getValue());
ByteArrayOutputStream baos;
switch(method) {
case GET:
connection.setDoInput(true);
connection.setDoOutput(false);
break;
case POST:
if (content != null) {
connection.setDoOutput(true);
baos = new ByteArrayOutputStream();
copy(content, baos);
writeRequestBody(connection, baos.toByteArray());
baos.close();
if (debugStream != null)
debugMid(debugBuffer, new String(baos.toByteArray()));
}
break;
case PUT:
if (content != null) {
connection.setDoOutput(true);
baos = new ByteArrayOutputStream();
copy(content, baos);
writeRequestBody(connection, baos.toByteArray());
baos.close();
if (debugStream != null)
debugMid(debugBuffer, new String(baos.toByteArray()));
}
break;
case DELETE:
connection.setDoInput(true);
break;
case HEAD:
connection.setDoInput(true);
connection.setDoOutput(false);
break;
default:
throw new RuntimeException("Unhandled HTTP method.");
}
if (debugStream != null)
debugEnd(debugBuffer);
return new Response<T>() {
private boolean done;
private boolean cancelled;
private StringBuilder responseBuffer;
@Override
public int getCode() throws IOException {
int code = connection.getResponseCode();
if (debugStream != null) {
responseBuffer = debugStart(code, connection.getResponseMessage());
}
return code;
}
@Override
public String getRequestUrl() {
return url;
}
@Override
public HttpMethod getRequestMethod() {
return method;
}
@Override
public HttpURLConnection getConnection() {
return connection;
}
@Override
public boolean isError() {
try {
int code = getCode();
return code >= HttpURLConnection.HTTP_BAD_REQUEST && code < HttpURLConnection.HTTP_VERSION;
} catch (IOException e) {
return true;
}
}
@Override
public boolean cancel(boolean flag) {
connection.disconnect();
cancelled = true;
if (responseBuffer != null) {
debugMid(responseBuffer, "[CANCELLED]");
debugEnd(responseBuffer);
}
return cancelled;
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public boolean isDone() {
return done;
}
@Override
public T getContent() throws IOException {
if (isError()) {
String serverMessage = getErrorMessage();
if (responseBuffer != null) {
debugMid(responseBuffer, serverMessage);
debugEnd(responseBuffer);
}
if (errorHandler != null)
errorHandler.handleError(getCode(), serverMessage);
if (deserializer != null)
return deserializer.deserialize(connection.getErrorStream(), connection.getResponseCode(),
connection.getHeaderFields());
return null;
}
if (deserializer == null) {
// If no deserializer is specified, use String.
T response = (T) RestClient.STRING_DESERIALIZER.deserialize(connection.getInputStream(), 0, null);
done = true;
if (responseBuffer != null) {
debugMid(responseBuffer, response.toString());
debugEnd(responseBuffer);
}
return response;
}
T response = deserializer.deserialize(connection.getInputStream(),
connection.getResponseCode(), connection.getHeaderFields());
done = true;
if (responseBuffer != null) {
debugEnd(responseBuffer);
}
return response;
}
@Override
public String getErrorMessage() {
try {
String errorMessage = connection.getResponseMessage();
byte[] serverMessage = readStream(connection.getErrorStream());
if (serverMessage != null && serverMessage.length > 0) {
if (connection.getContentEncoding() != null)
errorMessage = new String(serverMessage, connection.getContentEncoding());
else
errorMessage = new String(serverMessage, "UTF-8");
}
return errorMessage;
} catch (IOException e) {
return null;
}
}
};
}
private StringBuilder debugStart(String httpUrl, String httpMethod) {
StringBuilder debugBuffer = new StringBuilder();
debugBuffer.append(debugTimeFormat.format(new Date(System.currentTimeMillis())));
debugBuffer.append(' ');
debugBuffer.append(httpMethod.subSequence(0, 3));
debugBuffer.append(' ');
debugBuffer.append(httpUrl);
debugBuffer.append(' ');
return debugBuffer;
}
private StringBuilder debugStart(int responseCode, String responseMessage) {
StringBuilder debugBuffer = new StringBuilder();
debugBuffer.append(debugTimeFormat.format(new Date(System.currentTimeMillis())));
debugBuffer.append(' ');
debugBuffer.append("<-- ");
debugBuffer.append(responseCode);
debugBuffer.append(" ");
debugBuffer.append(responseMessage);
debugBuffer.append(' ');
return debugBuffer;
}
private void debugMid(StringBuilder debugBuffer, String element) {
debugBuffer.append(element);
debugBuffer.append(' ');
}
private void debugEnd(StringBuilder debugBuffer) {
debugStream.println(debugBuffer.toString());
debugStream.flush();
}
/**
* Execute GET method and return body as a string. This call blocks
* until the response content is deserialized into a String.
*
* @param url of server. If not String, toString() will be called.
* @return body as a String
* @throws IOException on I/O error
*/
public String callGet(Object url) throws IOException {
return callGetContent(url.toString(), STRING_DESERIALIZER);
}
/**
* Execute GET method and return body deserizalized. This call
* blocks until the response body content is deserialized.
*
* @param url of server. If not String, toString() will be called.
* @param deserializer ResponseDeserializer
* @return T deserialized object
* @throws IOException on I/O error
*/
public <T> T callGetContent(Object url, ResponseDeserializer<T> deserializer) throws IOException {
return call(HttpMethod.GET, url.toString(), deserializer, null, null).getContent();
}
/**
* Execute GET method and deserialize response.
*
* @param url of server If not String, toString() will be called.
* @param deserializer class that can deserialize content into desired type.
* @return type specified by deserializer
* @throws IOException on I/O error
*/
public <T> Response<T> callGet(Object url, Map<String, String> headers, ResponseDeserializer<T> deserializer) throws IOException {
return call(HttpMethod.GET, url.toString(), deserializer, null, headers);
}
/**
* Execute GET method and deserialize response.
*
* @param url of server. If not String, toString() will be called.
* @param deserializer class that can deserialize content into desired type.
* @return type specified by deserializer
* @throws IOException on I/O error
*/
public <T> Response<T> callGet(Object url, ResponseDeserializer<T> deserializer) throws IOException {
return call(HttpMethod.GET, url.toString(), deserializer, null, null);
}
/**
* Send a POST to the server.
*
* @param url url of server. If not String, toString() will be called.
* @param body body of post as an input stream
* @return a response to the request
* @throws IOException on I/O error
*/
public Response<Integer> callPost(Object url, InputStream body) throws IOException {
return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER, body, null);
}
/**
* Send a POST to the server.
*
* @param url url of server. If not String, toString() will be called.
* @param body body of post as a String
* @return a response to the request
* @throws IOException on I/O error
*/
public Response<Integer> callPost(Object url, String body) throws IOException {
return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER, new ByteArrayInputStream(body.getBytes()), null);
}
/**
* Send a POST to the server.
*
* @param url url of server
* @param formData Form data as strings.
* @return a response from the POST
* @throws IOException on I/O error
*/
public Response<Integer> callPost(Object url, Map<String, String> formData) throws IOException {
return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER,
new ByteArrayInputStream(propertyString(formData).getBytes()),
toMap(HEADER_CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED));
}
/**
* Send a POST to the server.
*
* @param url url of server
* @param body body of post as an input stream
* @return a response to the request
* @throws IOException on I/O error
*/
public <T> Response<T> callPost(Object url, InputStream body, ResponseDeserializer<T> deserializer) throws IOException {
return call(HttpMethod.POST, url.toString(), deserializer, body, null);
}
/**
* Send a POST to the server.
*
* @param url url of server. If not String, toString() will be called.
* @param formData Form data as strings.
* @return a response from the POST
* @throws IOException on I/O error
*/
public <T> Response<T> callPost(Object url, Map<String, String> formData, ResponseDeserializer<T> deserializer) throws IOException {
return call(HttpMethod.POST, url.toString(), deserializer,
new ByteArrayInputStream(propertyString(formData).getBytes()),
toMap(HEADER_CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED));
}
/**
* Send a POST to the server.
*
* @param <T> type to deserialize to
* @param url of server
* @param body of post
* @param headers additional headers for request
* @param deserializer deserializer
* @return response
* @throws IOException on I/O error
*/
public <T> Response<T> callPost(URLBuilder url, InputStream body, Map<String, String> headers, ResponseDeserializer<T> deserializer) throws IOException {
return call(HttpMethod.POST, url.toString(), deserializer, body, headers);
}
/**
* Send a multipart POST to the server. Convenience method for post(url, createMultipartPostBody(content)).
*
* @param url url of server. If not String, toString() will be called.
* @param content See createMultipartPostBody() for details on this parameter.
* @return a response from the POST
* @throws IOException on I/O error
*/
public Response<Integer> callPostMultipart(Object url, Map<String, Object> content) throws IOException {
String boundary = createMultipartBoundary();
String contentType = MULTIPART_FORM_DATA_CONTENT_TYPE + "; " + BOUNDARY + boundary;
return call(HttpMethod.POST, url.toString(), HTTP_CODE_DESERIALIZER,
createMultipartPostBody(boundary, content), toMap(HEADER_CONTENT_TYPE, contentType));
}
/**
* Send a multipart POST to the server. Convenience method for post(url, createMultipartPostBody(content)).
*
* @param url url of server. If not String, toString() will be called.
* @param content See createMultipartPostBody() for details on this parameter.
* @param deserializer class that can deserialize content into desired type.
* @param <T> Type to be deserialized to.
* @return a response from the POST
* @throws IOException on I/O error
*/
public <T> Response<T> callPostMultipart(Object url, Map<String, Object> content,
ResponseDeserializer<T> deserializer) throws IOException {
String boundary = createMultipartBoundary();
String contentType = MULTIPART_FORM_DATA_CONTENT_TYPE + "; " + BOUNDARY + boundary;
return call(HttpMethod.POST, url.toString(), deserializer,
createMultipartPostBody(boundary, content), toMap(HEADER_CONTENT_TYPE, contentType));
}
/**
* Call PUT method on a server.