Hello! 欢迎来到小浪资源网!


WebClient响应处理:如何根据返回类型区分逐条和一次性返回数据?


WebClient响应处理:如何根据返回类型区分逐条和一次性返回数据?

根据响应类型处理webclient响应

问题:

如何根据接口返回类型是text/Event-stream则逐条返回,否则一次性全部返回?

回答:

使用webclient的toentityflux,而不要使用exchangetomono或exchangetoflux。

WebClient webClient = WebClient.create();  Mono<ResponseEntity<String>> response = webClient.get()     .uri("http://example.com")     .retrieve()     .onStatus(HttpStatusCode::isError, clientResponse -> clientResponse.createException().flatMap(Mono::error))     .toEntityFlux(String.class)     .flatMap(responseEntity -> {         HttpHeaders headers2 = responseEntity.getHeaders();         MediaType contentType2 = headers2.getContentType();         if (MediaType.TEXT_EVENT_STREAM.isCompatibleWith(contentType2)) {             // SSE,逐条返回             return Mono.just(ResponseEntity.ok()                 .headers(headers2)                 .contentType(MediaType.TEXT_EVENT_STREAM)                 .body(Flux.from(Objects.requireNonNull(responseEntity.getBody()))));         } else {             // 非SSE,一次性返回响应体             return Objects.requireNonNull(responseEntity.getBody()).reduce("", String::concat)                 .map(body2 -> ResponseEntity.ok()                     .headers(headers2)                     .body(body2));         }     })     .onErrorResume(WebClientResponseException.class, e -> {         return Mono.just(ResponseEntity.status(e.getStatusCode())             .headers(e.getHeaders())             .body(e.getResponseBodyAsString()));     })     .onErrorResume(e -> {         // 处理其他异常         HttpHeaders errorHeaders = new HttpHeaders();         errorHeaders.set("error-status", "500");         errorHeaders.set("error-message", e.getMessage());         return Mono.just(ResponseEntity.status(500)             .headers(errorHeaders)             .body(Map.of(                 "status", "500",                 "error", "Internal Server Error",                 "message", e.getMessage()             )));     });

相关阅读