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

问题描述

我将Reactor Netty HTTP客户端here用作独立的依赖项,即不通过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文档here

可以看出

从示例中也可以使用数据

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响应正文。

我似乎找不到方法。有什么想法吗?qp

解决方法

看看以下方法:

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...