我必须从远程服务器获取一些JSON对象,为此我正在使用这个功能很好,除了有时一些奇怪的数据被提取,我相信是因为它使用ASCII字符集进行解码.
请在下面找到我正在使用的方法
public HttpResponse call(String serviceURL,String serviceHost,String namespace,String methodName,String payloadKey,String payloadValue) throws ClientProtocolException,IOException,JSONException
{
HttpResponse response = null;
HttpContext HTTP_CONTEXT = new BasicHttpContext();
HTTP_CONTEXT.setAttribute(CoreProtocolPNames.USER_AGENT,"Mozilla/5.0");
HttpPost httppost = new HttpPost(serviceURL);
httppost.setHeader("User-Agent",Constants.USER_AGENT_BROWSER_FIREFOX);
httppost.setHeader("Accept","application/json,text/javascript,*/*");
httppost.setHeader("Accept-Language","en-US,en;q=0.8");
httppost.setHeader("Content-Encoding","foo-1.0");
httppost.setHeader("Content-Type","application/json; charset=UTF-8");
httppost.setHeader("X-Requested-With","XMLHttpRequest");
httppost.setHeader("Host",serviceHost);
httppost.setHeader("X-Foo-Target",String.format("%s.%s",namespace,methodName));
/*Making Payload*/
JSONObject objectForPayload = new JSONObject();
objectForPayload.put(payloadKey,payloadValue);
StringEntity stringentity = new StringEntity(objectForPayload.toString());
httppost.setEntity(stringentity);
response = client.execute(httppost);
return response;
}
我传递的所有这些标题都是正确的,如果您熟悉Mozilla,我已通过Google Chrome或Firebug插件中的inspect元素验证了相同内容.
现在的问题是,大部分时间我都在获取可读数据,但有时我确实得到了不可读的数据.
我使用eclipse调试并注意到wrappedEntity下的charset显示为“US-ASCII”.我附上一个jpg作为参考
有人可以告诉我如何才能在响应之前将字符集从ASCII更改为UTF-8响应= client.execute(httppost); .
PS:正如你已经注意到我在标题中传递charset = utf-8并且我已经使用firebug和谷歌浏览器验证我传递了确切的标题.
请放大以更清楚地查看图像
提前致谢
最佳答案
原文链接:https://www.f2er.com/java/438213.html