我现在用的反应堆Netty的HTTP客户端在这里作为一个独立的依赖,也就是不通过spring-webflux
,因为我不想在春节相关的依赖拖累
从文档中可以看出,可以返回一个请求 HttpClientResponse
import reactor.netty.http.client.HttpClient;
import reactor.netty.http.client.HttpClientResponse;
public class Application {
public static void main(String[] args) {
HttpClientResponse response =
HttpClient.create()
.get()
.uri("http://example.com/")
.response()
.block();
}
}
事物HttpClientResponse
仅包含标题和状态。从这里的Java文档可以看出
同样从示例中可以使用数据
import reactor.netty.http.client.HttpClient;
public class Application {
public static void main(String[] args) {
String response =
HttpClient.create()
.get()
.uri("http://example.com/")
.responseContent()
.aggregate()
.asString()
.block();
}
}
但这只会将http实体数据返回为字符串。没有有关标题或状态码的信息。
我现在遇到的问题是,我需要发出一个请求并获得一个响应,该响应给我提供标头,状态等以及http响应正文。
我似乎找不到方法。有什么想法吗?
看一下以下方法:
Flux<V> response(BiFunction<HttpClientResponse,ByteBufFlux,Publisher<V>> receiver)
Mono<V> responseSingle(BiFunction<HttpClientResponse, ByteBufMono, Mono<V>> receiver)
它们使您可以同时访问响应正文,状态和http标头。
例如,使用该responseSingle
方法,您可以执行以下操作:
private Mono<Foo> getFoo() {
return httpClient.get()
.uri("foos/1")
.responseSingle(
(response, bytes) ->
bytes.asString()
.map(it -> new Foo(response.status().code(), it))
);
}
上面的代码将响应转换Foo
为如下定义的某些域对象:
public static class Foo {
int status;
String response;
public Foo(int status, String response) {
this.status = status;
this.response = response;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句