具有StringEntity的HttpPost具有特殊字符,如®,看到¿½`而不是®

时间:2013-12-09 15:07:20

标签: java character-encoding apache-httpclient-4.x

我需要使用stringentity的特殊字符,如下所示。

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();

响应中的输出包含test�而不是test®

2 个答案:

答案 0 :(得分:21)

更改为:

    HttpEntity entity = new StringEntity("test®", "UTF-8"); 

答案 1 :(得分:0)

我只使用了 ByteArrayEntity ,而不是使用 StringEntity

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