Phi*_*ohn 4 spring-boot spring-webclient spring5
我有以下代码
public ClientResponse doGet(HttpServletRequest request, URI uri) {
return webClient.get()
.uri(uri.toASCIIString())
.headers(headers -> headers.putAll(processRequest(request))
.exchange()
.block();
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试通过 RestController 返回此 ClientResponse 时,如下所示,
@GetMapping
@ResponseBody
public ClientResponse doGet(HttpServletRequest request) {
ClientResponse node = service.doGet(request);
return node;
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
org.springframework.http.converter.HttpMessageNotWritableException:找不到类型返回值的转换器:类org.springframework.web.reactive.function.client.DefaultClientResponse
基本上,我想要的最终目标是将实际响应返回给调用者 - 包括标头、正文、cookie等。
我正在考虑像下面这样使用 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;
}
Run Code Online (Sandbox Code Playgroud)
但这又是矫枉过正了。有没有办法直接使用WebClient返回响应而不是重构响应?
ClientResponse 的toEntity方法将其转换为 ResponseEntity<Mono> 对象。所以我想出了以下内容。
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16125 次 |
| 最近记录: |