[英]Spring WebClient: How to convert a HTTP response body to String for a specific encoding
I am using WebClient
of the Spring webflux module for the first time.我是第一次使用 Spring webflux 模块的
WebClient
。
The idea is to query a certain URL which gives me a CSV in shift-jis
encoding.我的想法是查询某个 URL,它给我一个 CSV 的
shift-jis
编码。
String content = webClient
.method(HttpMethod.GET)
.acceptCharset(Charset.forName("shift-jis"))
.uri(uri)
.accept(MediaType.TEXT_PLAIN, new MediaType("text", "csv"))
.retrieve()
.toEntity(String.class)
.mapNotNull(HttpEntity::getBody)
.block();
This works somewhat, but the content
String looks like it is in a wrong encoding - probably UTF-8.这有点管用,但
content
字符串看起来编码错误——可能是 UTF-8。
Alternatively, an Apache HttpClient
version seems to work:或者,Apache
HttpClient
版本似乎可以工作:
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(uri);
String content = IOUtils.toString(
client.execute(get).getEntity().getContent(),
Charset.forName("shift-jis"));
So I am wondering how one could interfere with the conversion happening in toEntity
.所以我想知道如何干扰
toEntity
中发生的转换。 I tried adding this to the webClient
call:我尝试将其添加到
webClient
调用中:
.codecs(configurer -> {
StringDecoder decoder = StringDecoder.textPlainOnly();
decoder.setDefaultCharset(Charset.forName("shift-jis"));
configurer.customCodecs().registerWithDefaultConfig(decoder);
})
Alas, this does not seem to be picked up.唉,这个好像没捡到。 Setting a breakpoint in
StringDecoder#decode
and manually overwriting the defaultCharset
field during debugging, however, does help.但是,在
StringDecoder#decode
中设置断点并在调试期间手动覆盖defaultCharset
字段确实有帮助。
Ah... Just after posting I realized: Maybe my custom text/csv
mime type is not really interpreted as textPlainOnly
.啊...发布后我意识到:也许我的自定义
text/csv
mime 类型并没有真正解释为textPlainOnly
。
And, indeed:而且,确实:
StringDecoder decoder = StringDecoder.allMimeTypes();
apparently does the trick.显然可以解决问题。
Leaving the question open in case my approach is awfully hacky and there are better/correct ways to tackle this issue.如果我的方法非常糟糕并且有更好/正确的方法来解决这个问题,请留下这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.