-
Notifications
You must be signed in to change notification settings - Fork 630
/
HttpClient.java
1605 lines (1514 loc) · 63 KB
/
HttpClient.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-2022 VMware, Inc. or its affiliates, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package reactor.netty.http.client;
import java.net.SocketAddress;
import java.net.URI;
import java.time.Duration;
import java.util.Objects;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import io.netty.buffer.ByteBuf;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMessage;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.cookie.ClientCookieDecoder;
import io.netty.handler.codec.http.cookie.ClientCookieEncoder;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.handler.codec.http.cookie.DefaultCookie;
import io.netty.handler.ssl.OpenSsl;
import io.netty.handler.ssl.SslContext;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;
import reactor.netty.ByteBufMono;
import reactor.netty.Connection;
import reactor.netty.ConnectionObserver;
import reactor.netty.NettyOutbound;
import reactor.netty.channel.ChannelMetricsRecorder;
import reactor.netty.http.Http2SettingsSpec;
import reactor.netty.http.HttpProtocol;
import reactor.netty.http.logging.HttpMessageLogFactory;
import reactor.netty.http.logging.ReactorNettyHttpMessageLogFactory;
import reactor.netty.http.websocket.WebsocketInbound;
import reactor.netty.http.websocket.WebsocketOutbound;
import reactor.netty.resources.ConnectionProvider;
import reactor.netty.tcp.SslProvider;
import reactor.netty.tcp.TcpClient;
import reactor.netty.transport.ClientTransport;
import reactor.util.Logger;
import reactor.util.Loggers;
import reactor.util.Metrics;
import reactor.util.annotation.Nullable;
/**
* An HttpClient allows building in a safe immutable way an http client that is
* materialized and connecting when {@link HttpClient#connect()} is ultimately called.
* {@code Transfer-Encoding: chunked} will be applied for those HTTP methods for which
* a request body is expected. {@code Content-Length} provided via request headers
* will disable {@code Transfer-Encoding: chunked}.
* <p>
* <p> Examples:
* <pre>
* {@code
* HttpClient.create()
* .baseUrl("https://example.com")
* .get()
* .response()
* .block();
* }
* {@code
* HttpClient.create()
* .post()
* .uri("https://example.com")
* .send(Flux.just(bb1, bb2, bb3))
* .responseSingle((res, content) -> Mono.just(res.status().code()))
* .block();
* }
* {@code
* HttpClient.create()
* .baseUri("https://example.com")
* .post()
* .send(ByteBufFlux.fromString(flux))
* .responseSingle((res, content) -> Mono.just(res.status().code()))
* .block();
* }
* </pre>
*
* @author Stephane Maldini
* @author Violeta Georgieva
*/
public abstract class HttpClient extends ClientTransport<HttpClient, HttpClientConfig> {
public static final String USER_AGENT = String.format("ReactorNetty/%s", reactorNettyVersion());
/**
* A URI configuration
*/
public interface UriConfiguration<S extends UriConfiguration<?>> {
/**
* Configure URI to use for this request/response
*
* @param uri target URI, if starting with "/" it will be prepended with
* {@link #baseUrl(String)} when available
*
* @return the appropriate sending or receiving contract
*/
S uri(String uri);
/**
* Configure URI to use for this request/response on subscribe
*
* @param uri target URI, if starting with "/" it will be prepended with
* {@link #baseUrl(String)} when available
*
* @return the appropriate sending or receiving contract
*/
S uri(Mono<String> uri);
/**
* Configure URI to use for this request/response.
* <p>Note: {@link #baseUrl(String)} will have no effect when this method is used for configuring an URI.
*
* @param uri target URI which is an absolute, fully constructed {@link URI}
* @return the appropriate sending or receiving contract
*/
S uri(URI uri);
}
/**
* Allow a request body configuration before calling one of the terminal, {@link
* Publisher} based, {@link ResponseReceiver} API.
*/
public interface RequestSender extends ResponseReceiver<RequestSender> {
/**
* Configure a body to send on request.
*
* <p><strong>Note:</strong> The body {@code Publisher} passed in will be invoked also for redirect requests
* when {@code followRedirect} is enabled. If you need to control what will be sent when
* {@code followRedirect} is enabled then use {@link #send(BiFunction)}.
* <p><strong>Note:</strong> For redirect requests, sensitive headers
* {@link #followRedirect(boolean, Consumer) followRedirect} are removed
* from the initialized request when redirecting to a different domain, they can be re-added globally via
* {@link #followRedirect(boolean, Consumer)}/{@link #followRedirect(BiPredicate, Consumer)}
* or alternatively for full control per redirect request, consider using {@link RedirectSendHandler}
* with {@link #send(BiFunction)}
*
* @param body a body publisher that will terminate the request on complete
*
* @return a new {@link ResponseReceiver}
*/
ResponseReceiver<?> send(Publisher<? extends ByteBuf> body);
/**
* Configure a body to send on request using the {@link NettyOutbound} sending
* builder and returning a {@link Publisher} to signal end of the request.
*
* <p><strong>Note:</strong> The sender {@code BiFunction} passed in will be invoked also for redirect requests
* when {@code followRedirect} is enabled. For redirect requests, sensitive headers
* {@link #followRedirect(boolean, Consumer) followRedirect} are removed
* from the initialized request when redirecting to a different domain, they can be re-added globally via
* {@link #followRedirect(boolean, Consumer)}/{@link #followRedirect(BiPredicate, Consumer)}
* or alternatively for full control per redirect request, consider using {@link RedirectSendHandler}.
* {@link RedirectSendHandler} can be used to indicate explicitly that this {@code BiFunction} has special
* handling for redirect requests.
*
* @param sender a bifunction given the outgoing request and the sending
* {@link NettyOutbound}, returns a publisher that will terminate the request
* body on complete
*
* @return a new {@link ResponseReceiver}
*/
ResponseReceiver<?> send(BiFunction<? super HttpClientRequest, ? super NettyOutbound, ? extends Publisher<Void>> sender);
/**
* Prepare to send an HTTP Form including Multipart encoded Form which support
* chunked file upload. It will by default be encoded as Multipart but can be
* adapted via {@link HttpClientForm#multipart(boolean)}.
*
* <p><strong>Note:</strong> The HTTP Form passed in will be invoked also for redirect requests
* when {@code followRedirect} is enabled. If you need to control what will be sent when
* {@code followRedirect} is enabled use {@link HttpClientRequest#redirectedFrom()} to check the original
* and any number of subsequent redirect(s), including the one that is in progress.
* <p><strong>Note:</strong> For redirect requests, sensitive headers
* {@link #followRedirect(boolean, Consumer) followRedirect} are removed
* from the initialized request when redirecting to a different domain, they can be re-added globally via
* {@link #followRedirect(boolean, Consumer)}/{@link #followRedirect(BiPredicate, Consumer)}.
*
* @param formCallback called when form generator is created
*
* @return a new {@link ResponseReceiver}
*/
default ResponseReceiver<?> sendForm(BiConsumer<? super HttpClientRequest, HttpClientForm> formCallback) {
return sendForm(formCallback, null);
}
/**
* Prepare to send an HTTP Form including Multipart encoded Form which support
* chunked file upload. It will by default be encoded as Multipart but can be
* adapted via {@link HttpClientForm#multipart(boolean)}.
*
* <p><strong>Note:</strong> The HTTP Form passed in will be invoked also for redirect requests
* when {@code followRedirect} is enabled. If you need to control what will be sent when
* {@code followRedirect} is enabled use {@link HttpClientRequest#redirectedFrom()} to check the original
* and any number of subsequent redirect(s), including the one that is in progress.
* <p><strong>Note:</strong> For redirect requests, sensitive headers
* {@link #followRedirect(boolean, Consumer) followRedirect} are removed
* from the initialized request when redirecting to a different domain, they can be re-added globally via
* {@link #followRedirect(boolean, Consumer)}/{@link #followRedirect(BiPredicate, Consumer)}.
*
* @param formCallback called when form generator is created
* @param progress called after form is being sent and passed with a {@link Flux} of the latest in-flight or uploaded bytes
*
* @return a new {@link ResponseReceiver}
*/
ResponseReceiver<?> sendForm(BiConsumer<? super HttpClientRequest, HttpClientForm> formCallback,
@Nullable Consumer<Flux<Long>> progress);
}
/**
* Allow a request body configuration before calling one of the terminal, {@link
* Publisher} based, {@link WebsocketReceiver} API.
*/
public interface WebsocketSender extends WebsocketReceiver<WebsocketSender> {
/**
* Configure headers to send on request using the returned {@link Publisher} to
* signal end of the request.
*
* @param sender a bifunction given the outgoing request returns a publisher
* that will terminate the request body on complete
*
* @return a new {@link ResponseReceiver}
*/
WebsocketReceiver<?> send(Function<? super HttpClientRequest, ? extends Publisher<Void>> sender);
}
/**
* A response extractor for this configured {@link HttpClient}. Since
* {@link ResponseReceiver} API returns {@link Flux} or {@link Mono},
* requesting is always deferred to {@link Publisher#subscribe(Subscriber)}.
*/
public interface ResponseReceiver<S extends ResponseReceiver<?>>
extends UriConfiguration<S> {
/**
* Return the response status and headers as {@link HttpClientResponse}
* <p> Will automatically close the response if necessary.
* <p>Note: Will automatically close low-level network connection after returned
* {@link Mono} terminates or is being cancelled.
*
* @return the response status and headers as {@link HttpClientResponse}
*/
Mono<HttpClientResponse> response();
/**
* Extract a response flux from the given {@link HttpClientResponse} and body
* {@link ByteBufFlux}.
* <p> Will automatically close the response if necessary after the returned
* {@link Flux} terminates or is being cancelled.
*
* @param receiver extracting receiver
* @param <V> the extracted flux type
*
* @return a {@link Flux} forwarding the returned {@link Publisher} sequence
*/
<V> Flux<V> response(BiFunction<? super HttpClientResponse, ? super ByteBufFlux, ? extends Publisher<V>> receiver);
/**
* Extract a response flux from the given {@link HttpClientResponse} and
* underlying {@link Connection}.
* <p> The connection will not automatically {@link Connection#dispose()} and
* manual interaction with this method might be necessary if the remote never
* terminates itself.
*
* @param receiver extracting receiver
* @param <V> the extracted flux type
*
* @return a {@link Flux} forwarding the returned {@link Publisher} sequence
*/
<V> Flux<V> responseConnection(BiFunction<? super HttpClientResponse, ? super Connection, ? extends Publisher<V>> receiver);
/**
* Return the response body chunks as {@link ByteBufFlux}.
*
* <p> Will automatically close the response if necessary after the returned
* {@link Flux} terminates or is being cancelled.
*
* @return the response body chunks as {@link ByteBufFlux}.
*/
ByteBufFlux responseContent();
/**
* Extract a response mono from the given {@link HttpClientResponse} and
* aggregated body {@link ByteBufMono}.
*
* <p> Will automatically close the response if necessary after the returned
* {@link Mono} terminates or is being cancelled.
*
* @param receiver extracting receiver
* @param <V> the extracted mono type
*
* @return a {@link Mono} forwarding the returned {@link Mono} result
*/
<V> Mono<V> responseSingle(BiFunction<? super HttpClientResponse, ? super ByteBufMono, ? extends Mono<V>> receiver);
}
/**
* Allow a websocket handling. Since {@link WebsocketReceiver} API returns
* {@link Flux} or {@link Mono}, requesting is always deferred to
* {@link Publisher#subscribe(Subscriber)}.
*/
public interface WebsocketReceiver<S extends WebsocketReceiver<?>> extends UriConfiguration<S> {
/**
* Negotiate a websocket upgrade and return a {@link Mono} of {@link Connection}. If
* {@link Mono} is cancelled, the underlying connection will be aborted. Once the
* {@link Connection} has been emitted and is not necessary anymore, disposing must be
* done by the user via {@link Connection#dispose()}.
*
* If update configuration phase fails, a {@link Mono#error(Throwable)} will be returned
*
* @return a {@link Mono} of {@link Connection}
*/
Mono<? extends Connection> connect();
/**
* Negotiate a websocket upgrade and extract a flux from the given
* {@link WebsocketInbound} and {@link WebsocketOutbound}.
* <p> The connection will not automatically {@link Connection#dispose()} and
* manual disposing with the {@link Connection},
* {@link WebsocketOutbound#sendClose}
* or the returned {@link Flux} might be necessary if the remote never
* terminates itself.
* <p> If the upgrade fails, the returned {@link Flux} will emit a
* {@link io.netty.handler.codec.http.websocketx.WebSocketHandshakeException}
*
* @param receiver extracting receiver
* @param <V> the extracted flux type
*
* @return a {@link Flux} of the extracted data via the returned {@link Publisher}
*/
<V> Flux<V> handle(BiFunction<? super WebsocketInbound, ? super WebsocketOutbound, ? extends Publisher<V>> receiver);
/**
* Negotiate a websocket upgrade and extract a flux from the underlying
* {@link WebsocketInbound}.
* <p> The connection will be disposed when the underlying subscriber is
* disposed OR when a close frame has been received, forwarding onComplete to
* the returned flux subscription.
* <p> If the upgrade fails, the returned {@link Flux} will emit a
* {@link io.netty.handler.codec.http.websocketx.WebSocketHandshakeException}
*
* @return a {@link ByteBufFlux} of the inbound websocket content
*/
ByteBufFlux receive();
}
/**
* Marker interface for use with {@link RequestSender#send(BiFunction)}.
* <p>When the {@code BiFunction} passed into {@code send} is an implementation of this
* interface, it indicates it differentiates between original and redirect requests,
* e.g. as a result of enabling {@link #followRedirect(boolean)}, and is capable of
* applying separate logic for each individually. Redirect scenarios may be detected
* by checking {@link HttpClientRequest#redirectedFrom()}.
* <p>When the {@code BiFunction} passed in is not an implementation of this interface,
* it indicates it does not differentiate between original and redirect requests, and
* applies the same initialization logic.
* @since 0.9.5
*/
public interface RedirectSendHandler extends BiFunction<HttpClientRequest, NettyOutbound, Publisher<Void>> {
}
/**
* Prepare a pooled {@link HttpClient}. {@link UriConfiguration#uri(String)} or
* {@link #baseUrl(String)} should be invoked before a verb
* {@link #request(HttpMethod)} is selected.
*
* @return a {@link HttpClient}
*/
public static HttpClient create() {
return new HttpClientConnect(new HttpConnectionProvider());
}
/**
* Prepare an {@link HttpClient}. {@link UriConfiguration#uri(String)} or
* {@link #baseUrl(String)} should be invoked before a verb
* {@link #request(HttpMethod)} is selected.
*
* @param connectionProvider the {@link ConnectionProvider} to be used
* @return a {@link HttpClient}
*/
public static HttpClient create(ConnectionProvider connectionProvider) {
Objects.requireNonNull(connectionProvider, "connectionProvider");
return new HttpClientConnect(new HttpConnectionProvider(connectionProvider));
}
/**
* Prepare an {@link HttpClient}
* <p>
* <strong>Note:</strong>
* There isn't only one method that replaces this deprecated method.
* The configuration that can be done with this deprecated method,
* can also be done with the other methods exposed by {@link HttpClient}.
* </p>
* <p>Examples:</p>
* <p>Configuration via the deprecated '.from(...)' method</p>
* <pre>
* {@code
* HttpClient.from(
* TcpClient.attr(...) // configures the channel attributes
* .bindAddress(...) // configures the bind (local) address
* .channelGroup(...) // configures the channel group
* .doOnChannelInit(...) // configures the channel handler
* .doOnConnected(...) // configures the doOnConnected callback
* .doOnDisconnected(...) // configures the doOnDisconnected callback
* .metrics(...) // configures the metrics
* .observe() // configures the connection observer
* .option(...) // configures the channel options
* .proxy(...) // configures the proxy
* .remoteAddress(...) // configures the remote address
* .resolver(...) // configures the host names resolver
* .runOn(...) // configures the event loop group
* .secure() // configures the SSL
* .wiretap()) // configures the wire logging
* }
* </pre>
*
* <p>Configuration via the other methods exposed by {@link HttpClient}</p>
* <pre>
* {@code
* HttpClient.attr(...) // configures the channel attributes
* .bindAddress(...) // configures the bind (local) address
* .channelGroup(...) // configures the channel group
* .doOnChannelInit(...) // configures the channel handler
* .doOnConnected(...) // configures the doOnConnected callback
* .doOnDisconnected(...) // configures the doOnDisconnected callback
* .metrics(...) // configures the metrics
* .observe() // configures the connection observer
* .option(...) // configures the channel options
* .proxy(...) // configures the proxy
* .remoteAddress(...) // configures the remote address
* .resolver(...) // configures the host names resolver
* .runOn(...) // configures the event loop group
* .secure() // configures the SSL
* .wiretap() // configures the wire logging
* }
* </pre>
*
* <p>Wire logging in plain text</p>
* <pre>
* {@code
* HttpClient.wiretap("logger", LogLevel.DEBUG, AdvancedByteBufFormat.TEXTUAL)
* }
* </pre>
*
* @return a new {@link HttpClient}
* @deprecated Use the other methods exposed by {@link HttpClient} to achieve the same configurations.
* This method will be removed in version 1.1.0.
*/
@Deprecated
public static HttpClient from(TcpClient tcpClient) {
Objects.requireNonNull(tcpClient, "tcpClient");
return HttpClientConnect.applyTcpClientConfig(tcpClient.configuration());
}
/**
* Prepare an unpooled {@link HttpClient}. {@link UriConfiguration#uri(String)} or
* {@link #baseUrl(String)} should be invoked after a verb
* {@link #request(HttpMethod)} is selected.
*
* @return a {@link HttpClient}
*/
public static HttpClient newConnection() {
return new HttpClientConnect(new HttpConnectionProvider(ConnectionProvider.newConnection()));
}
/**
* Configure URI to use for this request/response.
* <p>Note: Configured {@code baseUrl} only applies when used with {@link UriConfiguration#uri(String)}
* or {@link UriConfiguration#uri(Mono)}.
*
* @param baseUrl a default base url that can be fully sufficient for request or can
* be used to prepend future {@link UriConfiguration#uri} calls.
*
* @return the appropriate sending or receiving contract
*/
public final HttpClient baseUrl(String baseUrl) {
Objects.requireNonNull(baseUrl, "baseUrl");
HttpClient dup = duplicate();
dup.configuration().baseUrl = baseUrl;
return dup;
}
/**
* Specifies whether GZip compression is enabled.
*
* @param compressionEnabled if true GZip compression is enabled otherwise disabled (default: false)
* @return a new {@link HttpClient}
*/
public final HttpClient compress(boolean compressionEnabled) {
if (compressionEnabled) {
if (!configuration().acceptGzip) {
HttpClient dup = duplicate();
HttpHeaders headers = configuration().headers.copy();
headers.add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP);
dup.configuration().headers = headers;
dup.configuration().acceptGzip = true;
return dup;
}
}
else if (configuration().acceptGzip) {
HttpClient dup = duplicate();
if (isCompressing(configuration().headers)) {
HttpHeaders headers = configuration().headers.copy();
headers.remove(HttpHeaderNames.ACCEPT_ENCODING);
dup.configuration().headers = headers;
}
dup.configuration().acceptGzip = false;
return dup;
}
return this;
}
/**
* Apply cookies configuration.
*
* @param cookie a cookie to append to the request(s)
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookie(Cookie cookie) {
Objects.requireNonNull(cookie, "cookie");
if (!cookie.value().isEmpty()) {
HttpClient dup = duplicate();
HttpHeaders headers = configuration().headers.copy();
headers.add(HttpHeaderNames.COOKIE, dup.configuration().cookieEncoder.encode(cookie));
dup.configuration().headers = headers;
return dup;
}
return this;
}
/**
* Apply cookies configuration.
*
* @param cookieBuilder the header {@link Consumer} to invoke before requesting
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookie(String name, Consumer<? super Cookie> cookieBuilder) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(cookieBuilder, "cookieBuilder");
Cookie cookie = new DefaultCookie(name, "");
cookieBuilder.accept(cookie);
return cookie(cookie);
}
/**
* Configure the
* {@link ClientCookieEncoder}, {@link ClientCookieDecoder} will be
* chosen based on the encoder
*
* @param encoder the preferred ClientCookieEncoder
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookieCodec(ClientCookieEncoder encoder) {
Objects.requireNonNull(encoder, "encoder");
ClientCookieDecoder decoder = encoder == ClientCookieEncoder.LAX ?
ClientCookieDecoder.LAX : ClientCookieDecoder.STRICT;
return cookieCodec(encoder, decoder);
}
/**
* Configure the
* {@link ClientCookieEncoder} and {@link ClientCookieDecoder}
*
* @param encoder the preferred ClientCookieEncoder
* @param decoder the preferred ClientCookieDecoder
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookieCodec(ClientCookieEncoder encoder, ClientCookieDecoder decoder) {
Objects.requireNonNull(encoder, "encoder");
Objects.requireNonNull(decoder, "decoder");
HttpClient dup = duplicate();
dup.configuration().cookieEncoder = encoder;
dup.configuration().cookieDecoder = decoder;
return dup;
}
/**
* Apply cookies configuration emitted by the returned Mono before requesting.
*
* @param cookieBuilder the cookies {@link Function} to invoke before sending
*
* @return a new {@link HttpClient}
*/
public final HttpClient cookiesWhen(String name, Function<? super Cookie, Mono<? extends Cookie>> cookieBuilder) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(cookieBuilder, "cookieBuilder");
HttpClient dup = duplicate();
dup.configuration().deferredConf(config ->
cookieBuilder.apply(new DefaultCookie(name, ""))
.map(c -> {
if (!c.value().isEmpty()) {
HttpHeaders headers = configuration().headers.copy();
headers.add(HttpHeaderNames.COOKIE, config.cookieEncoder.encode(c));
config.headers = headers;
}
return config;
}));
return dup;
}
/**
* HTTP DELETE to connect the {@link HttpClient}.
*
* @return a {@link RequestSender} ready to prepare the content for response
*/
public final RequestSender delete() {
return request(HttpMethod.DELETE);
}
/**
* Option to disable {@code retry once} support for the outgoing requests that fail with
* {@link reactor.netty.channel.AbortedException#isConnectionReset(Throwable)}.
* <p>By default this is set to false in which case {@code retry once} is enabled.
*
* @param disableRetry true to disable {@code retry once}, false to enable it
*
* @return a new {@link HttpClient}
* @since 0.9.6
*/
public final HttpClient disableRetry(boolean disableRetry) {
if (disableRetry == configuration().retryDisabled) {
return this;
}
HttpClient dup = duplicate();
dup.configuration().retryDisabled = disableRetry;
return dup;
}
/**
* Setup a callback called when {@link HttpClientRequest} has been sent
* and {@link HttpClientState#REQUEST_SENT} has been emitted.
*
* @param doAfterRequest a callback called when {@link HttpClientRequest} has been sent
*
* @return a new {@link HttpClient}
*/
public final HttpClient doAfterRequest(BiConsumer<? super HttpClientRequest, ? super Connection> doAfterRequest) {
Objects.requireNonNull(doAfterRequest, "doAfterRequest");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientRequest, Connection> current =
(BiConsumer<HttpClientRequest, Connection>) configuration().doAfterRequest;
dup.configuration().doAfterRequest = current == null ? doAfterRequest : current.andThen(doAfterRequest);
return dup;
}
/**
* Setup a callback called after {@link HttpClientResponse} has been fully received
* and {@link HttpClientState#RESPONSE_COMPLETED} has been emitted.
*
* @param doAfterResponseSuccess a callback called after {@link HttpClientResponse} has been fully received
* and {@link HttpClientState#RESPONSE_COMPLETED} has been emitted.
*
* @return a new {@link HttpClient}
* @since 0.9.5
*/
public final HttpClient doAfterResponseSuccess(BiConsumer<? super HttpClientResponse, ? super Connection> doAfterResponseSuccess) {
Objects.requireNonNull(doAfterResponseSuccess, "doAfterResponseSuccess");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientResponse, Connection> current =
(BiConsumer<HttpClientResponse, Connection>) configuration().doAfterResponseSuccess;
dup.configuration().doAfterResponseSuccess = current == null ? doAfterResponseSuccess : current.andThen(doAfterResponseSuccess);
return dup;
}
/**
* Setup a callback called when {@link HttpClientRequest} has not been sent and when {@link HttpClientResponse} has not been fully
* received.
* <p>
* Note that some mutation of {@link HttpClientRequest} performed late in lifecycle
* {@link #doOnRequest(BiConsumer)} or {@link RequestSender#send(BiFunction)} might
* not be visible if the error results from a connection failure.
*
* @param doOnRequestError a consumer observing request failures
* @param doOnResponseError a consumer observing response failures
*
* @return a new {@link HttpClient}
*/
public final HttpClient doOnError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequestError,
BiConsumer<? super HttpClientResponse, ? super Throwable> doOnResponseError) {
Objects.requireNonNull(doOnRequestError, "doOnRequestError");
Objects.requireNonNull(doOnResponseError, "doOnResponseError");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientRequest, Throwable> currentRequestError =
(BiConsumer<HttpClientRequest, Throwable>) configuration().doOnRequestError;
dup.configuration().doOnRequestError =
currentRequestError == null ? doOnRequestError : currentRequestError.andThen(doOnRequestError);
@SuppressWarnings("unchecked")
BiConsumer<HttpClientResponse, Throwable> currentResponseError =
(BiConsumer<HttpClientResponse, Throwable>) configuration().doOnResponseError;
dup.configuration().doOnResponseError =
currentResponseError == null ? doOnResponseError : currentResponseError.andThen(doOnResponseError);
return dup;
}
/**
* Setup a callback called after {@link HttpClientResponse} headers have been
* received and the request is about to be redirected.
*
* <p>Note: This callback applies only if auto-redirect is enabled, e.g. via
* {@link HttpClient#followRedirect(boolean)}.
*
* @param doOnRedirect a callback called after {@link HttpClientResponse} headers have been received
* and the request is about to be redirected
*
* @return a new {@link HttpClient}
* @since 0.9.6
*/
public final HttpClient doOnRedirect(BiConsumer<? super HttpClientResponse, ? super Connection> doOnRedirect) {
Objects.requireNonNull(doOnRedirect, "doOnRedirect");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientResponse, Connection> current =
(BiConsumer<HttpClientResponse, Connection>) configuration().doOnRedirect;
dup.configuration().doOnRedirect = current == null ? doOnRedirect : current.andThen(doOnRedirect);
return dup;
}
/**
* Setup a callback called when {@link HttpClientRequest} is about to be sent
* and {@link HttpClientState#REQUEST_PREPARED} has been emitted.
*
* @param doOnRequest a callback called when {@link HttpClientRequest} is about to be sent
*
* @return a new {@link HttpClient}
*/
public final HttpClient doOnRequest(BiConsumer<? super HttpClientRequest, ? super Connection> doOnRequest) {
Objects.requireNonNull(doOnRequest, "doOnRequest");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientRequest, Connection> current =
(BiConsumer<HttpClientRequest, Connection>) configuration().doOnRequest;
dup.configuration().doOnRequest = current == null ? doOnRequest : current.andThen(doOnRequest);
return dup;
}
/**
* Setup a callback called when {@link HttpClientRequest} has not been sent.
* Note that some mutation of {@link HttpClientRequest} performed late in lifecycle
* {@link #doOnRequest(BiConsumer)} or {@link RequestSender#send(BiFunction)} might
* not be visible if the error results from a connection failure.
*
* @param doOnRequestError a consumer observing request failures
*
* @return a new {@link HttpClient}
*/
public final HttpClient doOnRequestError(BiConsumer<? super HttpClientRequest, ? super Throwable> doOnRequestError) {
Objects.requireNonNull(doOnRequestError, "doOnRequestError");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientRequest, Throwable> current =
(BiConsumer<HttpClientRequest, Throwable>) configuration().doOnRequestError;
dup.configuration().doOnRequestError = current == null ? doOnRequestError : current.andThen(doOnRequestError);
return dup;
}
/**
* Setup a callback called after {@link HttpClientResponse} headers have been
* received and {@link HttpClientState#RESPONSE_RECEIVED} has been emitted.
*
* @param doOnResponse a callback called after {@link HttpClientResponse} headers have been received
*
* @return a new {@link HttpClient}
*/
public final HttpClient doOnResponse(BiConsumer<? super HttpClientResponse, ? super Connection> doOnResponse) {
Objects.requireNonNull(doOnResponse, "doOnResponse");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientResponse, Connection> current =
(BiConsumer<HttpClientResponse, Connection>) configuration().doOnResponse;
dup.configuration().doOnResponse = current == null ? doOnResponse : current.andThen(doOnResponse);
return dup;
}
/**
* Setup a callback called when {@link HttpClientResponse} has not been fully
* received, {@link HttpClientState#RESPONSE_INCOMPLETE} has been emitted.
*
* @param doOnResponseError a consumer observing response failures
*
* @return a new {@link HttpClient}
*/
public final HttpClient doOnResponseError(BiConsumer<? super HttpClientResponse, ? super Throwable> doOnResponseError) {
Objects.requireNonNull(doOnResponseError, "doOnResponseError");
HttpClient dup = duplicate();
@SuppressWarnings("unchecked")
BiConsumer<HttpClientResponse, Throwable> current =
(BiConsumer<HttpClientResponse, Throwable>) configuration().doOnResponseError;
dup.configuration().doOnResponseError = current == null ? doOnResponseError : current.andThen(doOnResponseError);
return dup;
}
/**
* Enables auto-redirect support if the passed
* {@link java.util.function.Predicate} matches.
*
* <p><strong>Note:</strong> The passed {@link HttpClientRequest} and {@link HttpClientResponse}
* should be considered read-only and the implement SHOULD NOT consume or
* write the request/response in this predicate.
*
* <p><strong>Note:</strong> The sensitive headers {@link #followRedirect(BiPredicate, Consumer) followRedirect}
* are removed from the initialized request when redirecting to a different domain, they can be re-added
* via {@link #followRedirect(BiPredicate, Consumer)}.
*
* @param predicate that returns true to enable auto-redirect support.
* @return a new {@link HttpClient}
*/
public final HttpClient followRedirect(BiPredicate<HttpClientRequest, HttpClientResponse> predicate) {
return followRedirect(predicate, (Consumer<HttpClientRequest>) null);
}
/**
* Variant of {@link #followRedirect(BiPredicate)} that also accepts
* {@link BiConsumer} that provides the headers from the previous request and the current redirect request.
*
* <p><strong>Note:</strong> The sensitive headers:
* <ul>
* <li>Expect</li>
* <li>Cookie</li>
* <li>Authorization</li>
* <li>Proxy-Authorization</li>
* </ul>
* are removed from the initialized request when redirecting to a different domain,
* they can be re-added using the {@link BiConsumer}.
*
* @param predicate that returns true to enable auto-redirect support.
* @param redirectRequestBiConsumer {@link BiConsumer}, invoked on redirects, after
* the redirect request has been initialized, in order to apply further changes such as
* add/remove headers and cookies; use {@link HttpClientRequest#redirectedFrom()} to
* check the original and any number of subsequent redirect(s), including the one that
* is in progress. The {@link BiConsumer} provides the headers from the previous request
* and the current redirect request.
* @return a new {@link HttpClient}
* @since 0.9.12
*/
public final HttpClient followRedirect(BiPredicate<HttpClientRequest, HttpClientResponse> predicate,
@Nullable BiConsumer<HttpHeaders, HttpClientRequest> redirectRequestBiConsumer) {
Objects.requireNonNull(predicate, "predicate");
HttpClient dup = duplicate();
dup.configuration().followRedirectPredicate = predicate;
dup.configuration().redirectRequestBiConsumer = redirectRequestBiConsumer;
dup.configuration().redirectRequestConsumer = null;
return dup;
}
/**
* Variant of {@link #followRedirect(BiPredicate)} that also accepts a redirect request
* processor.
*
* <p><strong>Note:</strong> The sensitive headers:
* <ul>
* <li>Expect</li>
* <li>Cookie</li>
* <li>Authorization</li>
* <li>Proxy-Authorization</li>
* </ul>
* are removed from the initialized request when redirecting to a different domain,
* they can be re-added using {@code redirectRequestConsumer}.
*
* @param predicate that returns true to enable auto-redirect support.
* @param redirectRequestConsumer redirect request consumer, invoked on redirects, after
* the redirect request has been initialized, in order to apply further changes such as
* add/remove headers and cookies; use {@link HttpClientRequest#redirectedFrom()} to
* check the original and any number of subsequent redirect(s), including the one that
* is in progress.
* @return a new {@link HttpClient}
* @since 0.9.5
*/
public final HttpClient followRedirect(BiPredicate<HttpClientRequest, HttpClientResponse> predicate,
@Nullable Consumer<HttpClientRequest> redirectRequestConsumer) {
Objects.requireNonNull(predicate, "predicate");
HttpClient dup = duplicate();
dup.configuration().followRedirectPredicate = predicate;
dup.configuration().redirectRequestBiConsumer = null;
dup.configuration().redirectRequestConsumer = redirectRequestConsumer;
return dup;
}
/**
* Specifies whether HTTP status 301|302|303|307|308 auto-redirect support is enabled.
*
* <p><strong>Note:</strong> The sensitive headers {@link #followRedirect(boolean, Consumer) followRedirect}
* are removed from the initialized request when redirecting to a different domain, they can be re-added
* via {@link #followRedirect(boolean, Consumer)}.
*
* @param followRedirect if true HTTP status 301|302|307|308 auto-redirect support
* is enabled, otherwise disabled (default: false).
* @return a new {@link HttpClient}
*/
public final HttpClient followRedirect(boolean followRedirect) {
if (!followRedirect && configuration().followRedirectPredicate == null &&
configuration().redirectRequestConsumer == null &&
configuration().redirectRequestBiConsumer == null) {
return this;
}
return followRedirect(followRedirect, (Consumer<HttpClientRequest>) null);
}
/**
* Variant of {@link #followRedirect(boolean)} that also accepts
* {@link BiConsumer} that provides the headers from the previous request and the current redirect request.
*
* <p><strong>Note:</strong> The sensitive headers:
* <ul>
* <li>Expect</li>
* <li>Cookie</li>
* <li>Authorization</li>
* <li>Proxy-Authorization</li>
* </ul>
* are removed from the initialized request when redirecting to a different domain,
* they can be re-added using the {@link BiConsumer}.
*
* @param followRedirect if true HTTP status 301|302|307|308 auto-redirect support
* is enabled, otherwise disabled (default: false).
* @param redirectRequestBiConsumer {@link BiConsumer}, invoked on redirects, after
* the redirect request has been initialized, in order to apply further changes such as
* add/remove headers and cookies; use {@link HttpClientRequest#redirectedFrom()} to
* check the original and any number of subsequent redirect(s), including the one that
* is in progress. The {@link BiConsumer} provides the headers from the previous request
* and the current redirect request.
* @return a new {@link HttpClient}
* @since 0.9.12
*/
public final HttpClient followRedirect(boolean followRedirect,
@Nullable BiConsumer<HttpHeaders, HttpClientRequest> redirectRequestBiConsumer) {
if (followRedirect) {
return followRedirect(HttpClientConfig.FOLLOW_REDIRECT_PREDICATE, redirectRequestBiConsumer);
}
else {
HttpClient dup = duplicate();
dup.configuration().followRedirectPredicate = null;
dup.configuration().redirectRequestBiConsumer = null;
dup.configuration().redirectRequestConsumer = null;
return dup;
}
}
/**
* Variant of {@link #followRedirect(boolean)} that also accepts a redirect request
* processor.
*
* <p><strong>Note:</strong> The sensitive headers:
* <ul>
* <li>Expect</li>
* <li>Cookie</li>
* <li>Authorization</li>
* <li>Proxy-Authorization</li>
* </ul>
* are removed from the initialized request when redirecting to a different domain,
* they can be re-added using {@code redirectRequestConsumer}.
*
* @param followRedirect if true HTTP status 301|302|307|308 auto-redirect support
* is enabled, otherwise disabled (default: false).
* @param redirectRequestConsumer redirect request consumer, invoked on redirects, after
* the redirect request has been initialized, in order to apply further changes such as
* add/remove headers and cookies; use {@link HttpClientRequest#redirectedFrom()} to
* check the original and any number of subsequent redirect(s), including the one that
* is in progress.
* @return a new {@link HttpClient}
* @since 0.9.5
*/
public final HttpClient followRedirect(boolean followRedirect, @Nullable Consumer<HttpClientRequest> redirectRequestConsumer) {
if (followRedirect) {
return followRedirect(HttpClientConfig.FOLLOW_REDIRECT_PREDICATE, redirectRequestConsumer);
}
else {