原文:http://blog.csdn.net/qqaazz211/article/details/52136187
在网上看到了这篇比较简单的解决方法,果然有用,特记之
解决方法是:将 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(); }
具体原因博文:writeBytes()存在的问题
原因:out.writeBytes(content);该语句在转中文时候,已经变成乱码
public final void writeBytes(String s) throws IOException {
int len = s.length();
for (int i = 0 ; i < len ; i++) {
out.write((byte)s.charAt(i)); //高8位丢失
}
incCount(len);
}
因为Java里的char类型是16位的,一个char可以存储一个中文字符,在将其转换为 byte后高8位会丢失,这样就无法将中文字符完整的输出到输出流中。所以在可能有中文字符输出的地方最好先将其转换为字节数组,然后再通过write写入流,目前尝试过这种方法:把上面链接代码中的out.writeBytes(content);替换为out.write(content.getBytes());先把数据转成BYTE在写入流,执行成功,服务器接收正确的中文内容
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步