HttpURLConnection以post传数据时中文乱码的一个解决方法
2016-08-06 14:52
681 查看
今天在测试自己写的接口时,后台使用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.csdn.net/ananyangyang/article/details/8036800
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.csdn.net/ananyangyang/article/details/8036800
相关文章推荐
- 转载---HttpUrlConnection发送post请求汉字出现乱码的一个解决方法及其原因
- android HttpPost传JSON数据中文乱码的解决方法
- HttpUrlConnection post方法传递中文乱码问题
- 解决httpurlconnection获取网页数据部分中文乱码问题
- HttpUrlConnection post方法传递中文乱码问题
- Http Post请求提交json格式数据工具类,解决请求参数中文乱码问题
- HttpURLConnection使用POST方法参数乱码
- httpurlconnection post 和GET 分别传递2个参数给后台,返回JSON 解决乱码问题
- 关于Android使用HttpURLConnection传输含有中文JSON数据的报错、乱码问题
- 使用HttpURLConnection 的post方法来返回一个xml
- Java HttpURLConnection模拟请求Rest接口解决中文乱码问题
- Http请求post方法,请求和响应中文乱码问题的一点解决方法
- HttpURLConnection中文乱码解决
- 最近在搞fmx开发,用idhttp post 数据 返回中文乱码,在网上找了好多都解决不了,后来自己琢磨出方法,非常简单 uses IdGlobal lstr := idhttp1.Pos
- Java HttpURLConnection模拟请求Rest接口解决中文乱码问题
- http协议4---GET方式和POST方式获取表单数据举例3(统一方式获取,解决中文乱码问题)
- HttpURLConnection的URL包含中文字符时乱码的解决办法
- Java的HttpURLConnection通过POST请求中文乱码
- 解决HttpURLConnection请求时传中文参数乱码问题
- android post HttpURLConnection乱码解决