Special characters pose problems with REST webservice communication

限于喜欢 提交于 2019-12-20 05:34:15

问题


I am trying to post a JSON-object to a REST webservice from an Android application. Everything works fine until I add special characters like å, ä, ö.

JSONObject absenceObject = new JSONObject();
absenceObject.put(INFO_DESCRIPTION, "åka pendeltåg");
StringEntity entity = new StringEntity(absenceObject.toString());
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json";character);
httpPost.setHeader("Content-type", "application/json;charset=UTF-8");
HttpResponse response = httpclient.execute(httpPost);

If I print absenceObject.toString() and copy the result in to a regular rest client it works fine as well.


回答1:


Try specifying the desired charset in the StringEntity constructor:

StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");



回答2:


If you control both ends of the pipe, you can encode the REST text as shown here Encoding/decoding REST path parameters




回答3:


Re: Mark's response

Try specifying the desired charset in the StringEntity constructor:

StringEntity entity = new StringEntity(absenceObject.toString(), "UTF-8");

Note that setting charset after the constructor didn't work for me i.e.

entity.setContentEncoding("UTF-8");

I had to do as Mark said and set it in the constructor.

Michael




回答4:


byte[] buf = body.getBytes(HTTP.UTF_8);
wr.write(buf, 0, buf.length);

Try this it will work.



来源:https://stackoverflow.com/questions/5819431/special-characters-pose-problems-with-rest-webservice-communication

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