今天在测试自己写的接口时,后台使用HttpURLConnection,以post方式向服务器的接口传数据。但服务器得到的中文是乱码。度娘一早上没找到合适的解决方法。中午一觉醒来随便把
out.writeBytes(string); 改成 out.write(string.getBytes()); 就解决了。(简直是天了噜)。
改了之后的部分代码如下:
try {
URL url = new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
/**/
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
JSONObject obj = new JSONObject();
Map map = new HashMap();
map.put("name", "张三");
map.put("gender", "男");
obj.putAll(map);
String string = obj.toString();
out.write(string.getBytes());
//out.writeBytes(string);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
然后在这篇文章中找到了原因: http://blog.youkuaiyun.com/ananyangyang/article/details/8036800