project-reactor - 使用 Reactor Netty HTTP 客户端时如何获取 HTTP 响应正文和状态
问题描述
我在这里使用 Reactor Netty HTTP 客户端作为独立依赖项,即不是 via,spring-webflux
因为我不想拖入 Spring 相关的依赖项
从文档中可以看出,可以提出返回的请求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 Docs 可以看出
也可以从示例中消费数据
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 响应正文。
我似乎无法找到如何。有什么想法吗?qw
解决方案
看看以下方法:
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;
}
}
推荐阅读
- android - 如何在Android中实用地在面部或其他图像上绘制标志或在面部或其他图像上绘制或覆盖图像
- android - 下载 AOSP 代码时出现 ManifestInvalidRevisionError
- javascript - 如何正确更新 React 中的类名?
- javascript - Excel Web 添加对 Range.Load 函数的无效操作
- kubernetes - Kubernetes Let's Encrypt 不颁发证书
- java - Java将枚举列表连接到字符串
- javascript - 初学者:我将博客集成到我的 Javascript/React 网站中,但是如何添加样式?
- c++ - 在 C++ 中分别定义和初始化 List
- c# - 如何使用servicelocator wpf动态创建模型的多个实例
- amazon-web-services - 尝试导出发电机数据库表并写入 csv 文件时出现 UnicodeEncodeError