如何在Java中更改HTTP响应中的字符集编码

bou*_*rne 5 java http httpresponse character-encoding apache-httpclient-4.x

我必须从远程服务器获取一些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;


    }
Run Code Online (Sandbox Code Playgroud)

我传递的所有这些标题都是正确的,如果您熟悉Mozilla,我已通过Google Chrome或Firebug插件中的inspect元素验证了相同内容.

现在的问题是,大部分时间我都在获取可读数据,但有时我确实得到了不可读的数据.

我使用eclipse调试并注意到wrappedEntity下的charset显示为"US-ASCII".我附上一个jpg作为参考在此输入图像描述

有人可以告诉我如何在我之前将字符集从ASCII更改为UTF-8 response = client.execute(httppost);.PS:正如你已经注意到我在标题中传递charset = utf-8并且我已经使用firebug和谷歌浏览器验证我传递了确切的标题.

请放大以更清楚地查看图像

提前致谢

bou*_*rne 11

我能够解决这个问题,只是为可能面临类似问题的人提及它.获得响应后首先通过使用获取实体 HttpEntity entity = response.getEntity(); ,因为我的响应是一个json对象将实体转换为字符串,但使用"UTF-8"这样的东西 responseJsonObject = new JSONObject(EntityUtils.toString(entity,"UTF-8"));

以前我只是在做 responseJsonObject = new JSONObject(EntityUtils.toString(entity));


geb*_*eby 2

您可能需要添加“Accept-Encoding”标头并将其设置为“UTF-8”