brian661
brian661

Reputation: 548

Set Content-Charset in Apache HttpClient 4.x

I am switching my Apache Http Client from 3.x to 4.x.
For the old version, I use following to set my content charset .

DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectionTimeout);
...  // some more other setting.
httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, contentCharset);

Now I switched to 4.x, but I am not able finding the way to set the 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

Upvotes: 0

Views: 2595

Answers (1)

ok2c
ok2c

Reputation: 27538

The global protocol charset parameter is HC 3.x was silly.

Use ContentType to attribute of HttpEntity in order to correctly encode / decode the entity content.

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)) {
        }
    }
}

Upvotes: 1

Related Questions