故事:我有一个需求需要跨服务器去处理,然后将处理的结果通过json返回回来。我在远端服务器的controller上已经注解
@RequestMapping(value = "/addbyUrl", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
@ResponseBody
返回编码为UTF-8.
好了,我开始去读取
// 创建HttpClient实例
HttpClient httpclient = new DefaultHttpClient();
// 创建Get方法实例
HttpGet httpgets = null;
if (getOpenID) {
httpgets = new HttpGet("http://*******.com/?itemID="+param);
}else{
httpgets = new HttpGet("http://*******.com/?itemID="+param);
}
HttpResponse response;
try {
response = httpclient.execute(httpgets);
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
String json = "";
String inputLine;
try {
while ((inputLine = reader.readLine()) != null) {
json += inputLine;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
有趣的事情开始:
这里我return json; -----------》中文乱码
调试发现json为GBK编码,什么鬼,变种了!先不管,转码吧!
return new String(json.getBytes("GBK"),"UTF-8"); -----------》特殊符号乱码
直接调试远端服务器看看:Content-Type:application/json; charset=utf-8;所有文本正常。
继续设置HttpGet的编码:
httpGet.addHeader("Content-Type", "text/html;charset=UTF-8");
得到的结果依然如上。
开始检查自己的java 文件,环境的编码。尼玛,都是UTF-8的啊.......
慌了.......
翻HttpClient4的源代码:
.........
我的世界开始下雪,冷死我了!
HttpClient4中如果都没有设置编码,默认charset是ISO-8859-1。滚粗啊......
重写设置编码!
httpGet.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
读取也加个编码:
BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
return json;
闹一整天的BUG,解决了!