在 Apache HttpClient 中设置内容字符集 4.x
Set Content-Charset in Apache HttpClient 4.x
我正在将我的 Apache Http 客户端从 3.x 切换到 4.x。
对于旧版本,我使用以下设置我的内容字符集。
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);
... // some more other setting.
httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, contentCharset);
现在我切换到 4.x,但我找不到设置 http.protocol.content-charset 的方法。
httpClient = HttpClientBuilder.create().build();
Builder builder = RequestConfig.custom();
builder.setConnectionRequestTimeout(connectionTimeout);
... // some other setting
// no function to set the content charset
全局协议字符集参数是 HC 3.x 太傻了。
对 HttpEntity
的属性使用 ContentType
以便正确编码/解码实体内容。
CloseableHttpClient client = HttpClients.custom()
.build();
HttpPost httpPost = new HttpPost("https://httpbin.org/post");
httpPost.setEntity(new StringEntity("stuff", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)));
try (CloseableHttpResponse response = client.execute(httpPost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType contentType = ContentType.getOrDefault(entity);
try (Reader reader = new InputStreamReader(
entity.getContent(),
contentType.getCharset() != null ? contentType.getCharset() : StandardCharsets.UTF_8)) {
}
}
}
我正在将我的 Apache Http 客户端从 3.x 切换到 4.x。
对于旧版本,我使用以下设置我的内容字符集。
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);
... // some more other setting.
httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, contentCharset);
现在我切换到 4.x,但我找不到设置 http.protocol.content-charset 的方法。
httpClient = HttpClientBuilder.create().build();
Builder builder = RequestConfig.custom();
builder.setConnectionRequestTimeout(connectionTimeout);
... // some other setting
// no function to set the content charset
全局协议字符集参数是 HC 3.x 太傻了。
对 HttpEntity
的属性使用 ContentType
以便正确编码/解码实体内容。
CloseableHttpClient client = HttpClients.custom()
.build();
HttpPost httpPost = new HttpPost("https://httpbin.org/post");
httpPost.setEntity(new StringEntity("stuff", ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)));
try (CloseableHttpResponse response = client.execute(httpPost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
ContentType contentType = ContentType.getOrDefault(entity);
try (Reader reader = new InputStreamReader(
entity.getContent(),
contentType.getCharset() != null ? contentType.getCharset() : StandardCharsets.UTF_8)) {
}
}
}