有问题请教:
我将一个file中的json字符串取出,实例化一个StringEntiry,将json字符串写入请求体中。然后无论我以哪种编码方式输出StringEntity中的content,其中的中文均为乱码“???”。 这是怎么回事?
附上测试代码:
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost("some url");
post.addHeader("Content-Type", "application/json; charset=utf-8");
String requestContent = produceRequestContent();//这个方法返回的是上述json字符串。
StringEntity stringEntity = null;
try {
stringEntity = new StringEntity(requestContent);
stringEntity.setContentEncoding("utf-8");
post.setEntity(stringEntity);
InputStream input = stringEntity.getContent();
byte[] buffer = new byte[input.available()];
input.read(buffer);
String testStr = new String(buffer);
System.out.println(requestContent);
System.out.println(testStr);
System.out.println(EntityUtils.toString(stringEntity,"iso-8859-1"));
System.out.println(EntityUtils.toString(stringEntity,"gb2312"));
System.out.println(EntityUtils.toString(stringEntity,"gbk"));
System.out.println(EntityUtils.toString(stringEntity,"utf-8"));
} catch (Exception e) {
e.printStackTrace();
}
// 后面的execute省略了...
------解决方案--------------------
你这个字符串是怎么拿到的?
拿到的时候不需要解码?
你是不是中间已经用别的编码解过一次码了?