使用 Reactor Netty HTTP 客户端时如何同时获取 HTTP 响应 body 和状态

How to get both HTTP response body and Status when using Reactor Netty HTTP Client

我正在使用 Reactor Netty HTTP 客户端 here 作为独立的依赖项,即不通过 spring-webflux 因为我不想拖入 Spring 相关的依赖项

从文档中可以看出,可以提出 returns 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 只包含 headers 和状态。从它的 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();
    }
}

但这只是 returns 字符串形式的 http 实体数据。没有关于 headers 或状态代码的信息。

我现在遇到的问题是我需要发出一个请求并得到一个响应,该响应为我提供 headers、状态等以及 http 响应 body。

我好像找不到方法。有什么想法吗?qw

看看下面的方法:

它们允许您访问 响应 body状态http headers 同时.

例如,使用 responseSingle 方法,您可以执行以下操作:

private Mono<Foo> getFoo() {
    return httpClient.get()
            .uri("foos/1")
            .responseSingle(
                    (response, bytes) ->
                            bytes.asString()
                                    .map(it -> new Foo(response.status().code(), it))
            );
}

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

public static class Foo {
    int status;
    String response;

    public Foo(int status, String response) {
        this.status = status;
        this.response = response;
    }
}

当 http 响应没有正文时,Foo 对象为 null。例如,如果 HttpStatus 403 为 returned,则 Foo 对象为空。我能够检查响应代码和 return 状态。

(resp, bytes)-> {
  if (resp.status().code()=HttpResponseStatus.OK.code) {
        return bytes.asString().map(it->new Foo(resp.status(),it);
  } else {
        return Mono.just(new Foo(resp.status());
  }
}