我必须从远程服务器获取一些 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 插件中的检查元素验证了相同的标头。
现在的问题是,大多数时候我得到可读的数据,但有时我确实得到不可读的数据。
I debugged using eclipse and noticed that the charset under wrappedEntity is showing as "US-ASCII". I am attaching a jpg for reference
有人可以告诉我如何在执行之前将响应的字符集从 ASCII 更改为 UTF-8response = client.execute(httppost);
。
PS:正如您所注意到的,我在标头中传递了 charset=utf-8 并且我已经使用 firebug 和 google chrome 验证了我正在传递确切的标头。
请放大以更清楚地查看图像
提前致谢