使用 Reactor Netty HTTP Client 时如何获取 HTTP 响应正文和状态

Fin*_*ber 7 reactor project-reactor reactor-netty

我在这里使用 Reactor Netty HTTP 客户端作为独立依赖项,即不是通过,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();
    }
}
Run Code Online (Sandbox Code Playgroud)

事情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();
    }
}
Run Code Online (Sandbox Code Playgroud)

但这仅以字符串形式返回 http 实体数据。没有有关标头或状态代码的信息。

我现在遇到的问题是我需要发出请求并获得响应,该响应为我提供标头、状态等以及 http 响应正文。

我似乎无法找到如何。有什么想法吗?qw

cac*_*co3 3

看看以下方法:

它们允许您同时访问响应正文状态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))
            );
}
Run Code Online (Sandbox Code Playgroud)

上面的代码将响应转换Foo为定义如下的某个域对象:

public static class Foo {
    int status;
    String response;

    public Foo(int status, String response) {
        this.status = status;
        this.response = response;
    }
}
Run Code Online (Sandbox Code Playgroud)