您的位置:首页 > 理论基础 > 计算机网络

HttpClient用HttpPost传输中文字符串乱码

2016-01-06 20:01 465 查看
public static String getHttpRequestString(String url,String body) throws IOException {
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

StringEntity stringEntity = new StringEntity(body);
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");

HttpResponse response = client.execute(httpPost);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
StringBuffer jsonString = new StringBuffer();
while((line = bufferedReader.readLine()) != null) {
jsonString.append(line);
}
return jsonString.toString();
}

这是最初的代码,如果传输的body有中文汉字的话,如果对方设置的格式是UTF-8,那么他接收到的字符是乱码,

stringEntity.setContentEncoding("UTF-8");

加上这样一句代码,设置下格式就好了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: