25

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.

Italo Borssatto
  • 15,044
  • 7
  • 62
  • 88
java techie
  • 253
  • 1
  • 3
  • 6

3 Answers3

47

Change to:

    HttpEntity entity = new StringEntity("test®", "UTF-8"); 
Italo Borssatto
  • 15,044
  • 7
  • 62
  • 88
  • Thanks. This is working. new StringEntity("test®", "UTF-8") did the trick – java techie Dec 09 '13 at 15:32
  • Above solution is not working for me. It is showing [0xc3][0x83][0xe2][0x80][0x93] for Ö character. I using HttpEntity params =new StringEntity(xmlfileString,"UTF-8"); – Brijesh Jun 05 '17 at 08:11
  • 1
    @Brijesh Are you using System.out.prinln to read the data? Please, check the encoding used by the "tool" you're using to check the value. – Italo Borssatto Jun 05 '17 at 10:15
3

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);
Matheus Santz
  • 538
  • 6
  • 7
0

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");
Borja
  • 1,269
  • 1
  • 17
  • 30