使用Reactor Netty从HttpClient获取响应报文,以下介绍几种常用方法。
1.使用responseContent(),从block的返回中获取响应报文
HttpClient httpClient = HttpClient.create().wiretap(true);
String s0 = httpClient.post()//
.uri(URL) //
.send(ByteBufFlux.fromString(Mono.just("hello")))//
.responseContent()//
.aggregate()//
.asString()//
.block();
System.out.println("s0=" + s0);
这种方式的缺点是只能同步获取响应报文。
2.使用responseContent(),在doOnSuccess中获取响应报文
httpClient.post()//
.uri(URL) //
.send(ByteBufFlux.fromString(Mono.just("hello")))//
.responseContent()//
.aggregate()//
.asString()//
.doOnSuccess(s -> {
System.out.println("s1=" + s);
}).block();
3.使用responseContent(),在subscribe中获取响应报文
httpClient.post()//
.uri(URL) //
.send(ByteBufFlux.fromString(Mono.just("hello")))//
.responseContent()//
.aggregate()//
.asString()//
.subscribe(s -> {
System.out.println("s2=" + s);
});
4.使用responseSingle()
httpClient.post()//
.uri(URL)//
.send((request, nettyOutbound) -> {
return nettyOutbound.sendString(Mono.just("ok2"));
}).responseSingle((response, byteBufMono) -> {
return byteBufMono.asString().doOnSuccess(s -> {
System.out.println("s3=" + s);
});
}).block();
5.使用responseConnection()
httpClient.post()//
.uri(URL)//
.send((request, nettyOutbound) -> {
return nettyOutbound.sendString(Mono.just("ok2"));
}).responseConnection((response, conn) -> {
return conn.inbound().receive().aggregate().asString().doOnSuccess(s -> {
System.out.println("s4=" + s);
});
}).blockFirst();