特殊字符构成REST web服务通信问题

问题描述:

我有一个问题,我似乎无法自己弄清楚。特殊字符构成REST web服务通信问题

我想从Android应用程序发布JSON对象到REST web服务。一切工作正常,直到我添加像å,ä,ö这样的特殊字符。

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); 

如果我打印absenceObject.toString()并将结果复制到常规休息客户端,它工作正常。

我非常感谢任何帮助!

尝试指定所需的字符集在StringEntity构造:

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

非常感谢! – notBanana 2011-04-28 13:52:28

+0

StringEntity entity = new StringEntity(body,“UTF-8”); //wr.writeBytes(entity.toString()); wr.writeUTF(entity.toString());我曾尝试两种方式,但没有工作。提前致谢。 – 2016-04-13 06:04:08

如果你控制管道的两端,可以编码REST文本如下所示Encoding/decoding REST path parameters

回复:马克的响应

尝试在StringEntity构造函数中指定所需的字符集:

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

注意构造之后设置的字符集,我没有工作,即

entity.setContentEncoding("UTF-8"); 

我不得不做的马克说,并设置它在构造函数中。

迈克尔

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

试试这个它会工作。