我正在Android中开发一个应用程序,我可以插入新的评论(比如在facebook或任何其他社交网络中)。
执行此操作的功能如下:
public static String putNewComment(String comment, int userId, int trackId) throws IOException,JSONException {
HttpPost post = new HttpPost(Globals.PUBLISH_NEW_COMMENT);
StringEntity input = new StringEntity("{\"comment\": \""+comment+"\",\"trackId\":"+trackId+",\"userId\":"+userId+"}");
input.setContentType("application/json;charset=UTF-8");
post.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
post.setHeader("Accept", "application/json");
post.setEntity(input);
HttpResponse response = client.execute(post,Globals.localContext);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String resultMy="";
String line;
while ((line = rd.readLine()) != null) {
resultMy+=line;
System.out.println("Server says: "+line);
}
return resultMy;
}
每当我尝试添加包含é,ò等几个unicode字符的新评论时,我都会收到此错误:
com.fasterxml.jackson.databind.JsonMappingException:无效的UTF-8中间字节0x22
现在,我知道这个错误是因为内容编码是UTF-8而我正在尝试插入一个unicode字符。 问题是如何解决这个问题?我尝试通过这种方式改变:
input.setContentType("application/json;charset=UTF-16");
post.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-16"));
或
input.setContentType("application/json;charset=UTF-32");
post.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-32"));
但它不起作用! 请帮帮我