【问题标题】:Return the complete response using Spring WebClient使用 Spring WebClient 返回完整的响应
【发布时间】:2021-01-11 15:49:39
【问题描述】:

我有以下代码

public ClientResponse doGet(HttpServletRequest request, URI uri) {
    return webClient.get()
            .uri(uri.toASCIIString())
            .headers(headers -> headers.putAll(processRequest(request))
            .exchange()
            .block();
}

但是当我尝试如下通过 RestController 返回这个 ClientResponse 时,

@GetMapping
@ResponseBody
public ClientResponse doGet(HttpServletRequest request) {
    ClientResponse node = service.doGet(request);
    return node;
}

我收到以下错误:

org.springframework.http.converter.HttpMessageNotWritableException: 否 找到类型返回值的转换器:类 org.springframework.web.reactive.function.client.DefaultClientResponse

基本上,我想要的最终目标是将实际响应返回给调用者 - 包括标头、正文、cookies 等。

我正在考虑像下面这样使用 ResponseEntity。

public ResponseEntity<JsonNode> doGet2(HttpServletRequest request, URI uri) {

    Mono<ClientResponse> clientResponse = webClient.get()
            .uri(uri.toASCIIString())
            .headers(headers -> headers.putAll(processRequest(request))
            .exchange();

    HttpHeaders headers = clientResponse.map(resp -> resp.headers().asHttpHeaders()).block();
    JsonNode body = clientResponse.flatMap(resp -> resp.bodyToMono(JsonNode.class)).block();

    ResponseEntity<JsonNode> jsonNode = ResponseEntity.ok().headers(headers).body(body);
    return jsonNode;
}

但这又是矫枉过正。有没有办法直接使用 WebClient 返回响应而不是重构响应?

【问题讨论】:

    标签: spring-boot spring-webclient spring5


    【解决方案1】:

    ClientResponse 的 toEntity 方法将其转换为 ResponseEntity 对象。 所以我想出了以下内容。

    public ResponseEntity<String> doGet2(HttpServletRequest request, URI uri) {
        ClientResponse clientResponse = webClient.get()
                .uri(uri.toASCIIString())
                .headers(headers -> headers.putAll(processRequest(request)))
                .exchange()
                .block();
    
        return clientResponse.toEntity(String.class).block();
    }
    

    【讨论】:

    • 似乎不起作用,我收到错误“block()/blockFirst()/blockLast() 正在阻塞,线程 reactor-http-epoll-2 不支持”
    • @aswzen 是的,我遇到了同样的错误。您找到解决方案了吗?如何读取客户端响应并返回?
    • @VikiCullen 我正在使用另一种解决方法,例如 Flux 作为拦截器并使用 doOnComplete() 打印内容
    【解决方案2】:

    通常,当您将 pojo 作为 responseBody 返回时,spring 要求该类具有字段的 getter。现在,由于您没有返回自己拥有的课程,因此无法添加它们。
    其他解决方案可以是向您的项目添加一个库,将 pojo 转换为 json。这个可以解决问题:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.0</version>
    </dependency>
    

    【讨论】:

    • 其实我已经添加了jackson依赖并没有修复它。
    猜你喜欢
    • 2019-03-22
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2020-11-24
    • 1970-01-01
    相关资源
    最近更新 更多