转载---HttpUrlConnection发送post请求汉字出现乱码的一个解决方法及其原因

原文: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在写入流,执行成功,服务器接收正确的中文内容

原文地址:https://www.cnblogs.com/f91og/p/6817604.html