我必須從遠程服務器中獲取一些JSON對象,並且我正在使用這個功能非常棒,除了某些奇怪的數據正在被抓取,我相信是因爲它使用ASCII字符集來解碼。我如何更改Java中的HTTP響應中的字符集編碼
請在下面找到THW方法,我使用
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;
}
所有這些標題,我想過去是正確的,我已經驗證了同樣的通過檢查在谷歌Chrome或螢火蟲插件元素,如果你熟悉的Mozilla 。
現在的問題是,大部分時間我正在獲取可讀數據,但有時我確實得到了無法讀取的數據。
我使用eclipse進行調試,並注意到wrappedEntity下的字符集顯示爲「US-ASCII」。我附上一個JPG作爲參考
有人可以告訴我如何將字符集從ASCII轉換爲UTF-8的響應之前我做response = client.execute(httppost);
。 PS:正如你已經注意到,我在標題中傳遞字符集= utf-8,並且我已經驗證了使用螢火蟲和谷歌瀏覽器,我傳遞了確切的標題。
請放大才能看到圖像更清晰
在此先感謝
我試過,但它沒有工作相同的結果'httppost.setHeader(「Accept-Encoding」,「UTF-8」);' – bourne