-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
HTTPExamples.java
1485 lines (1207 loc) · 43.3 KB
/
HTTPExamples.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) 2011-2019 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http:https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package examples;
import io.netty.handler.codec.compression.GzipOptions;
import io.netty.handler.codec.compression.StandardCompressionOptions;
import io.vertx.core.*;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.FileSystem;
import io.vertx.core.file.OpenOptions;
import io.vertx.core.http.*;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.endpoint.LoadBalancer;
import io.vertx.core.net.NetSocket;
import io.vertx.core.net.ProxyOptions;
import io.vertx.core.net.ProxyType;
import io.vertx.core.net.endpoint.EndpointNode;
import io.vertx.core.streams.Pipe;
import io.vertx.core.streams.ReadStream;
import java.util.List;
/**
* Created by tim on 09/01/15.
*/
public class HTTPExamples {
public void example1(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
}
public void example2(Vertx vertx) {
HttpServerOptions options = new HttpServerOptions().setMaxWebSocketFrameSize(1000000);
HttpServer server = vertx.createHttpServer(options);
}
public void exampleServerLogging(Vertx vertx) {
HttpServerOptions options = new HttpServerOptions().setLogActivity(true);
HttpServer server = vertx.createHttpServer(options);
}
public void example3(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
server.listen();
}
public void example4(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
server.listen(8080, "myhost.com");
}
public void example5(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
server
.listen(8080, "myhost.com")
.onComplete(res -> {
if (res.succeeded()) {
System.out.println("Server is now listening!");
} else {
System.out.println("Failed to bind!");
}
});
}
public void example6(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
server.requestHandler(request -> {
// Handle the request in here
});
}
public void example7(Vertx vertx) {
HttpServer server = vertx.createHttpServer();
server.requestHandler(request -> {
// Handle the request in here
HttpMethod method = request.method();
});
}
public void example7_1(Vertx vertx) {
vertx.createHttpServer().requestHandler(request -> {
request.response().end("Hello world");
}).listen(8080);
}
public void example8(HttpServerRequest request) {
MultiMap headers = request.headers();
// Get the User-Agent:
System.out.println("User agent is " + headers.get("user-agent"));
// You can also do this and get the same result:
System.out.println("User agent is " + headers.get("User-Agent"));
}
public void example9(HttpServerRequest request) {
request.handler(buffer -> {
System.out.println("I have received a chunk of the body of length " + buffer.length());
});
}
public void example10(HttpServerRequest request) {
// Create an empty buffer
Buffer totalBuffer = Buffer.buffer();
request.handler(buffer -> {
System.out.println("I have received a chunk of the body of length " + buffer.length());
totalBuffer.appendBuffer(buffer);
});
request.endHandler(v -> {
System.out.println("Full body received, length = " + totalBuffer.length());
});
}
public void example11(HttpServerRequest request) {
request.bodyHandler(totalBuffer -> {
System.out.println("Full body received, length = " + totalBuffer.length());
});
}
public void example12(HttpServer server) {
server.requestHandler(request -> {
request.setExpectMultipart(true);
request.endHandler(v -> {
// The body has now been fully read, so retrieve the form attributes
MultiMap formAttributes = request.formAttributes();
});
});
}
public void example13(HttpServer server) {
server.requestHandler(request -> {
request.setExpectMultipart(true);
request.uploadHandler(upload -> {
System.out.println("Got a file upload " + upload.name());
});
});
}
public void example14(HttpServerRequest request) {
request.uploadHandler(upload -> {
upload.handler(chunk -> {
System.out.println("Received a chunk of the upload of length " + chunk.length());
});
});
}
public void example15(HttpServerRequest request) {
request.uploadHandler(upload -> {
upload.streamToFileSystem("myuploads_directory/" + upload.filename());
});
}
public void exampleHandlingCookies(HttpServerRequest request) {
Cookie someCookie = request.getCookie("mycookie");
String cookieValue = someCookie.getValue();
// Do something with cookie...
// Add a cookie - this will get written back in the response automatically
request.response().addCookie(Cookie.cookie("othercookie", "somevalue"));
}
public void example16(HttpServerRequest request, Buffer buffer) {
HttpServerResponse response = request.response();
response.write(buffer);
}
public void example17(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.write("hello world!");
}
public void example18(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.write("hello world!", "UTF-16");
}
public void example19(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.write("hello world!");
response.end();
}
public void example20(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.end("hello world!");
}
public void example21(HttpServerRequest request) {
HttpServerResponse response = request.response();
MultiMap headers = response.headers();
headers.set("content-type", "text/html");
headers.set("other-header", "wibble");
}
public void example22(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.putHeader("content-type", "text/html").putHeader("other-header", "wibble");
}
public void example23(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.setChunked(true);
}
public void example24(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.setChunked(true);
MultiMap trailers = response.trailers();
trailers.set("X-wibble", "woobble").set("X-quux", "flooble");
}
public void example25(HttpServerRequest request) {
HttpServerResponse response = request.response();
response.setChunked(true);
response.putTrailer("X-wibble", "woobble").putTrailer("X-quux", "flooble");
}
public void example26(Vertx vertx) {
vertx.createHttpServer().requestHandler(request -> {
String file = "";
if (request.path().equals("/")) {
file = "index.html";
} else if (!request.path().contains("..")) {
file = request.path();
}
request.response().sendFile("web/" + file);
}).listen(8080);
}
public void example26b(Vertx vertx) {
vertx.createHttpServer().requestHandler(request -> {
long offset = 0;
try {
offset = Long.parseLong(request.getParam("start"));
} catch (NumberFormatException e) {
// error handling...
}
long end = Long.MAX_VALUE;
try {
end = Long.parseLong(request.getParam("end"));
} catch (NumberFormatException e) {
// error handling...
}
request.response().sendFile("web/mybigfile.txt", offset, end);
}).listen(8080);
}
public void example26c(Vertx vertx) {
vertx.createHttpServer().requestHandler(request -> {
long offset = 0;
try {
offset = Long.parseLong(request.getParam("start"));
} catch (NumberFormatException e) {
// error handling...
}
request.response().sendFile("web/mybigfile.txt", offset);
}).listen(8080);
}
public void example27(Vertx vertx) {
vertx.createHttpServer().requestHandler(request -> {
HttpServerResponse response = request.response();
if (request.method() == HttpMethod.PUT) {
response.setChunked(true);
request.pipeTo(response);
} else {
response.setStatusCode(400).end();
}
}).listen(8080);
}
public void sendHttpServerResponse(Vertx vertx) {
vertx.createHttpServer().requestHandler(request -> {
HttpServerResponse response = request.response();
if (request.method() == HttpMethod.PUT) {
response.send(request);
} else {
response.setStatusCode(400).end();
}
}).listen(8080);
}
public void example28(Vertx vertx) {
HttpClientAgent client = vertx.createHttpClient();
}
public void example29(Vertx vertx) {
HttpClientOptions options = new HttpClientOptions().setKeepAlive(false);
HttpClientAgent client = vertx.createHttpClient(options);
}
public void examplePoolConfiguration(Vertx vertx) {
PoolOptions options = new PoolOptions().setHttp1MaxSize(10);
HttpClientAgent client = vertx.createHttpClient(options);
}
public void exampleClientLogging(Vertx vertx) {
HttpClientOptions options = new HttpClientOptions().setLogActivity(true);
HttpClientAgent client = vertx.createHttpClient(options);
}
public void exampleClientBuilder01(Vertx vertx, HttpClientOptions options) {
// Pretty much like vertx.createHttpClient(options)
HttpClientAgent build = vertx
.httpClientBuilder()
.with(options)
.build();
}
public void example30(HttpClient client) {
client
.request(HttpMethod.GET, 8080, "myserver.mycompany.com", "/some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
// Connected to the server
}
});
}
public void example31(Vertx vertx) {
// Set the default host
HttpClientOptions options = new HttpClientOptions().setDefaultHost("wibble.com");
// Can also set default port if you want...
HttpClientAgent client = vertx.createHttpClient(options);
client
.request(HttpMethod.GET, "/some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
request
.send()
.onComplete(ar2 -> {
if (ar2.succeeded()) {
HttpClientResponse response = ar2.result();
System.out.println("Received response with status code " + response.statusCode());
}
});
}
});
}
public void example32(Vertx vertx) {
HttpClientAgent client = vertx.createHttpClient();
// Write some headers using the headers multi-map
MultiMap headers = HttpHeaders.set("content-type", "application/json").set("other-header", "foo");
client
.request(HttpMethod.GET, "some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
request.headers().addAll(headers);
request
.send()
.onComplete(ar2 -> {
HttpClientResponse response = ar2.result();
System.out.println("Received response with status code " + response.statusCode());
});
}
}
});
}
public void example33(HttpClientRequest request) {
// Write some headers using the putHeader method
request.putHeader("content-type", "application/json")
.putHeader("other-header", "foo");
}
public void sendRequest01(HttpClient client) {
client
.request(HttpMethod.GET, 8080, "myserver.mycompany.com", "/some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
// Send the request and process the response
request
.send()
.onComplete(ar -> {
if (ar.succeeded()) {
HttpClientResponse response = ar.result();
System.out.println("Received response with status code " + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
});
}
public void sendRequest02(HttpClient client) {
client
.request(HttpMethod.GET, 8080, "myserver.mycompany.com", "/some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
// Send the request and process the response
request
.send("Hello World")
.onComplete(ar -> {
if (ar.succeeded()) {
HttpClientResponse response = ar.result();
System.out.println("Received response with status code " + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
});
}
public void sendRequest03(HttpClientRequest request) {
// Send the request and process the response
request
.send(Buffer.buffer("Hello World"))
.onComplete(ar -> {
if (ar.succeeded()) {
HttpClientResponse response = ar.result();
System.out.println("Received response with status code " + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
public void sendRequest04(HttpClientRequest request, ReadStream<Buffer> stream) {
// Send the request and process the response
request
.putHeader(HttpHeaders.CONTENT_LENGTH, "1000")
.send(stream)
.onComplete(ar -> {
if (ar.succeeded()) {
HttpClientResponse response = ar.result();
System.out.println("Received response with status code " + response.statusCode());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
}
public void example34(Vertx vertx, String body) {
HttpClientAgent client = vertx.createHttpClient();
client.request(HttpMethod.POST, "some-uri")
.onSuccess(request -> {
request.response().onSuccess(response -> {
System.out.println("Received response with status code " + response.statusCode());
});
// Now do stuff with the request
request.putHeader("content-length", "1000");
request.putHeader("content-type", "text/plain");
request.write(body);
// Make sure the request is ended when you're done with it
request.end();
});
}
public void example35(HttpClientRequest request) {
// Write string encoded in UTF-8
request.write("some data");
// Write string encoded in specific encoding
request.write("some other data", "UTF-16");
// Write a buffer
Buffer buffer = Buffer.buffer();
buffer.appendInt(123).appendLong(245l);
request.write(buffer);
}
public void example36(HttpClientRequest request) {
// Write string and end the request (send it) in a single call
request.end("some simple data");
// Write buffer and end the request (send it) in a single call
Buffer buffer = Buffer.buffer().appendDouble(12.34d).appendLong(432l);
request.end(buffer);
}
public void example39(HttpClientRequest request) {
request.end();
}
public void example40(HttpClientRequest request) {
// End the request with a string
request.end("some-data");
// End it with a buffer
Buffer buffer = Buffer.buffer().appendFloat(12.3f).appendInt(321);
request.end(buffer);
}
public void example41(HttpClientRequest request) {
request.setChunked(true);
// Write some chunks
for (int i = 0; i < 10; i++) {
request.write("this-is-chunk-" + i);
}
request.end();
}
public void clientIdleTimeout(HttpClient client, int port, String host, String uri, int timeoutMS) {
Future<Buffer> fut = client
.request(new RequestOptions()
.setHost(host)
.setPort(port)
.setURI(uri)
.setIdleTimeout(timeoutMS))
.compose(request -> request.send().compose(HttpClientResponse::body));
}
public void clientConnectTimeout(HttpClient client, int port, String host, String uri, int timeoutMS) {
Future<Buffer> fut = client
.request(new RequestOptions()
.setHost(host)
.setPort(port)
.setURI(uri)
.setConnectTimeout(timeoutMS))
.compose(request -> request.send().compose(HttpClientResponse::body));
}
public void clientTimeout(HttpClient client, int port, String host, String uri, int timeoutMS) {
Future<Buffer> fut = client
.request(new RequestOptions()
.setHost(host)
.setPort(port)
.setURI(uri)
.setTimeout(timeoutMS))
.compose(request -> request.send().compose(HttpClientResponse::body));
}
public void useRequestAsStream(HttpClientRequest request) {
request.setChunked(true);
request.write("chunk-1");
request.write("chunk-2");
request.end();
}
public void setRequestExceptionHandler(HttpClientRequest request) {
request.exceptionHandler(err -> {
System.out.println("Write failure " + err.getMessage());
});
}
public void example44(HttpClientRequest request, AsyncFile file) {
request.setChunked(true);
file.pipeTo(request);
}
public void example45(HttpClientRequest request) {
// Send the request
request
.send()
.onComplete(ar2 -> {
if (ar2.succeeded()) {
HttpClientResponse response = ar2.result();
// the status code - e.g. 200 or 404
System.out.println("Status code is " + response.statusCode());
// the status message e.g. "OK" or "Not Found".
System.out.println("Status message is " + response.statusMessage());
}
});
}
public void example46(HttpClientResponse response) {
String contentType = response.headers().get("content-type");
String contentLength = response.headers().get("content-lengh");
}
public void example47(HttpClient client) {
client
.request(HttpMethod.GET, "some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
request
.send()
.onComplete(ar2 -> {
HttpClientResponse response = ar2.result();
response.handler(buffer -> {
System.out.println("Received a part of the response body: " + buffer);
});
});
}
});
}
public void example48(HttpClientRequest request) {
request
.send()
.onComplete(ar2 -> {
if (ar2.succeeded()) {
HttpClientResponse response = ar2.result();
// Create an empty buffer
Buffer totalBuffer = Buffer.buffer();
response.handler(buffer -> {
System.out.println("Received a part of the response body: " + buffer.length());
totalBuffer.appendBuffer(buffer);
});
response.endHandler(v -> {
// Now all the body has been read
System.out.println("Total response body length is " + totalBuffer.length());
});
}
});
}
public void example49(HttpClientRequest request) {
request
.send()
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientResponse response = ar1.result();
response
.body()
.onComplete(ar2 -> {
if (ar2.succeeded()) {
Buffer body = ar2.result();
// Now all the body has been read
System.out.println("Total response body length is " + body.length());
}
});
}
});
}
private interface HttpClient2 {
Future<HttpClientResponse> get(String requestURI);
}
public void exampleClientComposition01(HttpClient2 client) throws Exception {
Future<HttpClientResponse> get = client.get("some-uri");
// Assuming we have a client that returns a future response
// assuging this is *not* on the event-loop
// introduce a potential data race for the sake of this example
Thread.sleep(100);
get.onSuccess(response -> {
// Response events might have happen already
response
.body()
.onComplete(ar -> {
});
});
}
// Seems to fail javac in CI
// public void exampleClientComposition02(Vertx vertx, HttpClient client) throws Exception {
//
// vertx.deployVerticle(() -> new AbstractVerticle() {
// @Override
// public void start() {
//
// HttpClient client = vertx.createHttpClient();
//
// Future<HttpClientRequest> future = client.request(HttpMethod.GET, "some-uri");
// }
// }, new DeploymentOptions());
// }
public void exampleClientComposition03(HttpClient client) throws Exception {
Future<JsonObject> future = client
.request(HttpMethod.GET, "some-uri")
.compose(request -> request
.send()
.compose(response -> {
// Process the response on the event-loop which guarantees no races
if (response.statusCode() == 200 &&
response.getHeader(HttpHeaders.CONTENT_TYPE).equals("application/json")) {
return response
.body()
.map(buffer -> buffer.toJsonObject());
} else {
return Future.failedFuture("Incorrect HTTP response");
}
}));
// Listen to the composed final json result
future.onSuccess(json -> {
System.out.println("Received json result " + json);
}).onFailure(err -> {
System.out.println("Something went wrong " + err.getMessage());
});
}
public void exampleClientComposition03_(HttpClient client) throws Exception {
Future<JsonObject> future = client
.request(HttpMethod.GET, "some-uri")
.compose(request -> request
.send()
.expecting(HttpResponseExpectation.SC_OK.and(HttpResponseExpectation.JSON))
.compose(response -> response
.body()
.map(buffer -> buffer.toJsonObject())));
// Listen to the composed final json result
future.onSuccess(json -> {
System.out.println("Received json result " + json);
}).onFailure(err -> {
System.out.println("Something went wrong " + err.getMessage());
});
}
public void exampleClientComposition04(HttpClient client, FileSystem fileSystem) throws Exception {
Future<Void> future = client
.request(HttpMethod.GET, "some-uri")
.compose(request -> request
.send()
.compose(response -> {
// Process the response on the event-loop which guarantees no races
if (response.statusCode() == 200) {
// Create a pipe, this pauses the response
Pipe<Buffer> pipe = response.pipe();
// Write the file on the disk
return fileSystem
.open("/some/large/file", new OpenOptions().setWrite(true))
.onFailure(err -> pipe.close())
.compose(file -> pipe.to(file));
} else {
return Future.failedFuture("Incorrect HTTP response");
}
}));
}
public void usingPredefinedExpectations(HttpClient client, RequestOptions options) {
Future<Buffer> fut = client
.request(options)
.compose(request -> request
.send()
.expecting(HttpResponseExpectation.SC_SUCCESS)
.compose(response -> response.body()));
}
public void usingPredicates(HttpClient client) {
// Check CORS header allowing to do POST
HttpResponseExpectation methodsPredicate =
resp -> {
String methods = resp.getHeader("Access-Control-Allow-Methods");
return methods != null && methods.contains("POST");
};
// Send pre-flight CORS request
client
.request(new RequestOptions()
.setMethod(HttpMethod.OPTIONS)
.setPort(8080)
.setHost("myserver.mycompany.com")
.setURI("/some-uri")
.putHeader("Origin", "Server-b.com")
.putHeader("Access-Control-Request-Method", "POST"))
.compose(request -> request
.send()
.expecting(methodsPredicate))
.onSuccess(res -> {
// Process the POST request now
})
.onFailure(err ->
System.out.println("Something went wrong " + err.getMessage()));
}
public void usingSpecificStatus(HttpClient client, RequestOptions options) {
client
.request(options)
.compose(request -> request
.send()
.expecting(HttpResponseExpectation.status(200, 202)))
.onSuccess(res -> {
// ....
});
}
public void usingSpecificContentType(HttpClient client, RequestOptions options) {
client
.request(options)
.compose(request -> request
.send()
.expecting(HttpResponseExpectation.contentType("some/content-type")))
.onSuccess(res -> {
// ....
});
}
public void expectationCustomError() {
Expectation<HttpResponseHead> expectation = HttpResponseExpectation.SC_SUCCESS
.wrappingFailure((resp, err) -> new MyCustomException(resp.statusCode(), err.getMessage()));
}
private static class MyCustomException extends Exception {
private final int code;
public MyCustomException(int code, String message) {
super(message);
this.code = code;
}
}
public void exampleFollowRedirect01(HttpClient client) {
client
.request(HttpMethod.GET, "some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
request.setFollowRedirects(true);
request
.send()
.onComplete(ar2 -> {
if (ar2.succeeded()) {
HttpClientResponse response = ar2.result();
System.out.println("Received response with status code " + response.statusCode());
}
});
}
});
}
public void exampleFollowRedirect02(Vertx vertx) {
HttpClientAgent client = vertx.createHttpClient(
new HttpClientOptions()
.setMaxRedirects(32));
client
.request(HttpMethod.GET, "some-uri")
.onComplete(ar1 -> {
if (ar1.succeeded()) {
HttpClientRequest request = ar1.result();
request.setFollowRedirects(true);
request
.send()
.onComplete(ar2 -> {
if (ar2.succeeded()) {
HttpClientResponse response = ar2.result();
System.out.println("Received response with status code " + response.statusCode());
}
});
}
});
}
private String resolveURI(String base, String uriRef) {
throw new UnsupportedOperationException();
}
public void exampleFollowRedirect03(Vertx vertx) {
HttpClientAgent client = vertx.httpClientBuilder()
.withRedirectHandler(response -> {
// Only follow 301 code
if (response.statusCode() == 301 && response.getHeader("Location") != null) {
// Compute the redirect URI
String absoluteURI = resolveURI(response.request().absoluteURI(), response.getHeader("Location"));
// Create a new ready to use request that the client will use
return Future.succeededFuture(new RequestOptions().setAbsoluteURI(absoluteURI));
}
// We don't redirect
return null;
})
.build();
}
public void example50(HttpClient client) {
client.request(HttpMethod.PUT, "some-uri")
.onSuccess(request -> {
request.response().onSuccess(response -> {
System.out.println("Received response with status code " + response.statusCode());
});
request.putHeader("Expect", "100-Continue");
request.continueHandler(v -> {
// OK to send rest of body
request.write("Some data");
request.write("Some more data");
request.end();
});
request.sendHead();
});
}
public void example50_1(HttpServer httpServer) {
httpServer.requestHandler(request -> {
if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) {
// Send a 100 continue response
request.response().writeContinue();
// The client should send the body when it receives the 100 response
request.bodyHandler(body -> {
// Do something with body
});
request.endHandler(v -> {
request.response().end();
});
}
});
}
public void example50_2(HttpServer httpServer) {
httpServer.requestHandler(request -> {
if (request.getHeader("Expect").equalsIgnoreCase("100-Continue")) {
//