POST操作使用JSON产生400外文字符 [英] POSTing foreign characters using JSON produces 400

查看:246
本文介绍了POST操作使用JSON产生400外文字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让使用JSON与国外字符,如用'〜'在它的西班牙N A POST请求,但我不断收到这种请求和响应错误:

I'm trying to make a POST request using JSON with foreign characters, such as the Spanish n with the '~' over it, but I keep getting this request and response error:

POST ...
Accept: application/json
Content-Type: application/json; charset=UTF-8
Content-Length: 151
Content-Encoding: UTF-8
Host: ...
Connection: Keep-Alive
User-Agent: ..

{"numbers":"2","date":"2014-07-15T00:00:00+0000","description":" // this never gets closed

X-Powered-By: ...
Set-Cookie: ...
Cache-Control: ...
Date: Tue, 15 Jul 2014 15:19:12 GMT
Content-Type: application/json
Allow: GET, POST

{"status":"error",
"status_code":400,
"status_text":"Bad Request",
"current_content":"",
"message":"Could not decode JSON, malformed UTF-8 characters (incorrectly encoded?)"}

我已经可以做用普通的ASCII字符,一个成功的POST请求,但现在,我支持外语,我需要将外文字符转换为UTF-8(或任何正确的编码最终被),除非有一个更好的方式来做到这一点。

I can already make a successful POST request with normal ASCII characters, but now that I'm supporting foreign languages, I need to convert the foreign characters to UTF-8 (or whatever the correct encoding ends up being), unless there's a better way to do this.

下面是我的code:

JSONObject jsonObject = new JSONObject();
HttpResponse resp = null;
String urlrest = // some url;
HttpPost p = new HttpPost(urlrest);
HttpClient hc = new DefaultHttpClient();
hc = sslClient(hc);

try
{
   p.setHeader("Accept", "application/json");
   p.setHeader("Content-Type", "application/json");

   // setting TimeZone stuff

   jsonObject.put("date", date);
   jsonObject.put("description", description);
   jsonObject.put("numbers", numbers);

   String seStr = jsonObject.toString();
   StringEntity se = new StringEntity(seStr);
   // Answer: The above line becomes new StringEntity(seStr, "UTF-8");

   Header encoding = se.getContentType();
   se.setContentEncoding("UTF-8");
   se.setContentType("application/json");
   p.setEntity(se);
   resp = hc.execute(p);

当我把一个断点,并期待在本质上它是在提交前,人物看的权利。

When I put a breakpoint and look at se before it's submitted, the characters look right.

更新: code。与答案更新行数以上评论识别它

UPDATE: code updated with answer a few lines above with a comment identifying it.

感谢您的帮助!
德文

Thanks for your help! Devin

推荐答案

新StringEntity 构造函数采用UTF-8参数。

The new StringEntity constructor takes a "UTF-8" parameter.

这篇关于POST操作使用JSON产生400外文字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆