How can i change charset encoding in HTTP response in Java

孤街醉人 提交于 2019-12-01 18:11:10

i was able to resolve the issue just mentioning it for people that may face similar issue. after getting the response first get the entity by using HttpEntity entity = response.getEntity(); and since my response was a json object convert entity to string but using "UTF-8" something like this responseJsonObject = new JSONObject(EntityUtils.toString(entity,"UTF-8"));

previously i was just doing responseJsonObject = new JSONObject(EntityUtils.toString(entity));

You may need to add an "Accept-Encoding"-header and set this to "UTF-8"

I don't think it's a problem with your headers, I think it's a problem with your string. Just having the header say it's utf-8 doesn't mean the string you write is utf-8, and that depends a lot on how the string was encoded and what's in the "payloadValue"

That said, you can always re-encode the thing correctly before sending it across the wire, for example:

objectForPayload.put(payloadKey, payloadValue);
StringEntity stringentity = new StringEntity(
   new String(
      objectForPayload.toString().getBytes(),
      "UTF8"));

See if that works for you.

Just for the record: the "Content-Encoding" header field is incorrect - a correct server would reject the request as it contains an undefined content coding format.

Furthermore, attaching a charset parameter to application/json is meaningless.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!