netty HttpClient

netty httpclient support http/2.

HTTP/2

ref: https://projectreactor.io/docs/netty/release/reference/index.html#_http2_2

By default, the HTTP client supports HTTP/1.1. If you need HTTP/2, you can get it through configuration. In addition to the protocol configuration, if you need H2 but not H2C (cleartext), you must also configure SSL.

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
import io.netty.handler.codec.http.HttpHeaders;
import reactor.core.publisher.Mono;
import reactor.netty.http.HttpProtocol;
import reactor.netty.http.client.HttpClient;
import reactor.util.function.Tuple2;

public class H2Application {

public static void main(String[] args) {
HttpClient client =
HttpClient.create()
.protocol(HttpProtocol.H2)
.secure();

Tuple2<String, HttpHeaders> response =
client.get()
.uri("https://example.com/")
.responseSingle((res, bytes) -> bytes.asString()
.zipWith(Mono.just(res.responseHeaders())))
.block();

System.out.println("Used stream ID: " + response.getT2().get("x-http2-stream-id"));
System.out.println("Response: " + response.getT1());
}
}

simple usage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
HttpClient.create()
.baseUrl("https://example.com")
.get()
.response()
.block();


HttpClient.create()
.post()
.uri("https://example.com")
.send(Flux.just(bb1, bb2, bb3))
.responseSingle((res, content) -> Mono.just(res.status().code()))
.block();


HttpClient.create()
.baseUri("https://example.com")
.post()
.send(ByteBufFlux.fromString(flux))
.responseSingle((res, content) -> Mono.just(res.status().code()))
.block();

参考文章

评论