我必须从远程服务器获取一些 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 插件中的检查元素验证了相同的标题。
现在的问题是,大多数时候我都得到了可读数据,但有时我得到了不可读的数据。
我使用 eclipse 进行调试,并注意到 WrappedEntity 下的字符集显示为“US-ASCII”。我附上一张jpg供参考
有人可以告诉我如何在我做之前将响应的字符集从 ASCII 更改为 UTF-8 response = client.execute(httppost);
。PS:正如您所注意到的,我在标题中传递了 charset=utf-8 并且我已经使用 firebug 和 google chrome 验证了我正在传递确切的标题。
请放大以更清楚地看到图像
提前致谢