HttpPost with StringEntity having special characters like ®, seeing ¿½` instead of ®

Viewed 19635

I need to use special characters for stringentity as below.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpEntity entity = new StringEntity("test®");
httpPost.setEntity(entity);
httpPost.setHeader("Accept-Encoding", "UTF-8");

HttpResponse response = httpClient.execute(httpPost);
BufferedReader reader =  new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
while ((reader.readLine()) != null) {
    System.out.println (reader.readLine());
}
reader.close();

The output contains test� instead of test® in the response.

3 Answers

Instead of StringEntity, I'm using ByteArrayEntity:

String string = "ã@í";
HttpEntity httpEntity = new ByteArrayEntity(string.getBytes("UTF-8"));
request.addHeader("Content-type", "application/xml;charset=UTF-8");
request.setEntity(httpEntity);

In my case, I was already using the answer code, but adding this did the trick (I saw it in the question text)

httpPost.setHeader("Accept-Encoding", "UTF-8");
Related