I am trying to make a POST request using JSON with foreign characters, for example, Spanish n with the inscription "~", but I continue to receive 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 support foreign languages, I need to convert the foreign characters to UTF-8 (or whatever the correct encoding ends), if only the best way to do this .
Here is 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 place a breakpoint and look at it before its presentation, the characters look right.
UPDATE: updated with a response a few lines above with a comment identifying it.
Thanks for your help! Devin
java json android rest
craned Jul 15 '14 at 15:48 2014-07-15 15:48
source share