首页 > 解决方案 > 使用 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

标签: project-reactorreactorreactor-netty

解决方案


看看以下方法:

它们允许您同时访问响应正文状态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;
    }
}

推荐阅读