【发布时间】:2021-04-27 22:49:25
【问题描述】:
我正在使用org.apache.http 包进行休息呼叫,如下所示。我希望在回复中以英语和其他国际语言提供用户个人资料详细信息。
HttpGet req = new HttpGet(baseUrl + uri);
HttpResponse res= closeableHttpClient.execute(req);
响应具有 UTF-8 作为字符集,这正是我想要的。从这里开始,我使用了 2 种方法来解组对地图的响应。
方法一:
String response = EntityUtils.toString(res.getEntity(),"UTF-8");
// String response = EntityUtils.toString(httpResponse.getEntity(),Charset.forName("UTF-8"));
map = jsonConversionUtil.convertStringtoMap(response);
问题:
httpResponse.getEntity() 正在返回 StringEntity 对象,该对象的默认字符集为 ISO_8859_1,但即使我强制转换为 UTF-8(上面的未注释行和注释行,我都尝试过),我无法覆盖转为 UTF-8。
方法二:
HttpEntity responseEntity = res.getEntity();
if (responseEntity != null ) {
InputStream contentStream = responseEntity.getContent();
if (contentStream != null) {
String response = IOUtils.toString(contentStream, "UTF-8");
map = jsonConversionUtil.convertStringtoMap(response);
}
}
问题:
IOUtils.toString(contentStream, "UTF-8"); 未设置为 UT8。
我正在使用 httpclient 4.3.2 jar 和 httpcore-4.3.1 jar。 Java 6 中使用的 Java 版本。我无法升级到更高的 Java 版本。
您能否指导我如何设置为 UTF-8 格式。
【问题讨论】:
标签: utf-8 character-encoding httpclient apache-httpclient-4.x utf-16