使用Spring WebClient解码内容编码gzip
作者:互联网
我正在使用Spring WebClient(Spring 5.1.3)调用Web服务.服务以内容类型响应:application / json和内容编码:gzip
然后,ClientResponse.bodyToMono失败,并显示错误“ JSON解码错误:非法字符((CTRL-CHAR,代码31))”,我认为这是因为在尝试解析JSON之前尚未对内容进行解码.
这是我如何创建WebClient的代码段(简化)
HttpClient httpClient = HttpClient.create().secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
return WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)).build();
然后,我使用WebClient进行呼叫:
webClient.get().uri(uri)
.accept(MediaType.APPLICATION_JSON)
.header(HttpHeaders.ACCEPT_ENCODING, "gzip")
.exchange()
HTTP请求具有2个标头:
Accept: application/json
Accept-Encoding: gzip
响应具有以下标头:
set-cookie: xxx
content-type: application/json; charset=utf-8
content-length: 1175
content-encoding: gzip
cache-control: no-store, no-cache
通过执行以下操作,我能够手动解码GZIP内容并从结果中获取有效的JSON
webClient.get().uri(uri)
.accept(MediaType.APPLICATION_JSON)
.header("accept-encoding", "gzip")
.exchange()
.flatMap(encodedResponse -> encodedResponse.body((inputMessage, context) ->
inputMessage.getBody().flatMap(dataBuffer -> {
ClientResponse.Builder decodedResponse = ClientResponse.from(encodedResponse);
try {
GZIPInputStream gz = new GZIPInputStream(dataBuffer.asInputStream());
decodedResponse.body(new String(gz.readAllBytes()));
} catch (IOException e) {
e.printStackTrace();
}
decodedResponse.headers(headers -> {
headers.remove("content-encoding");
});
return Mono.just(decodedResponse.build());
}).flatMap(clientResponse -> clientResponse.bodyToMono(Map.class))
解决方法:
反应堆净额客户端本机支持此功能.
您应该这样创建HttpClient:
HttpClient httpClient = HttpClient.create()
.secure(sslContextSpec -> sslContextSpec.sslContext(sslContext))
.compress(true);
然后,无需添加接受编码请求标头,因为它已经为您完成.
请注意,当您不提供自定义HttpClient实例时为this bit is done by the connector itself.
标签:spring-webflux,reactor-netty,spring 来源: https://codeday.me/bug/20191024/1923755.html