我尝试使用带有外来字符的 JSON 发出 POST 请求,例如带有“~”的西类牙语 n,但我不断收到此请求和响应错误:
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(或任何正确的编码最终是什么),除非有更好的方法来做到这一点。
这是我的代码:
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);
当我在提交之前设置断点并查看 se 时,字符看起来是正确的。
更新:代码更新为上面几行的答案以及标识它的注释。
最佳答案
new StringEntity
构造函数采用“UTF-8”参数。
关于java - 使用 JSON POST 外来字符会产生 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762641/