Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

java - POSTing foreign characters using JSON produces 400

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?)"}

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.

Here's my 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...