java - 使用 JSON POST 外来字符会产生 400

标签 java android json rest

我尝试使用带有外来字符的 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/

相关文章:

java - 如何使用 sh() 命令在 Jenkinsfile 中设置 ENV 变量

java - 需要不兼容的类型 :boolean found:int

java - Android:seekbar.setProgress() 给出 Nullpointer 异常

java - 查询具有类似子类关系的表

objective-c - 解析 JSON objective c

java - 尝试只使用一个方法名称

java - 使用 getter 或将它们分配给变量是否更有效?

java - 从 Android 设备访问 SQL DB 时,我的 httpEntity 返回 null,任何人都可以告诉我这是为什么吗?

php - 如何从 mysql/php 中的 json 对象中选择数据?

mysql - qooxdoo 远程请求未完成