HttpURLConnection发送中文乱码问题解决

简介: HttpURLConnection发送中文乱码问题解决

/**

 * 发送http POST请求
 *
 * @param
 * @return 远程响应结果
 */
public static String sendPost(String u, String json) throws Exception {
    StringBuffer sbf = new StringBuffer();
    try {
        URL url = new URL(u);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        connection.connect();
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        if (!"".equals(json)) {
            //out.writeBytes(json);
            out.write(json.getBytes());
        }
        out.flush();
        out.close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String lines;
        while ((lines = reader.readLine()) != null) {
            lines = new String(lines.getBytes(), "utf-8");
            sbf.append(lines);
        }
        System.out.println(sbf);
        reader.close();
        // 断开连接
        connection.disconnect();
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
    return sbf.toString();
}

重点在于:替换out.writeBytes(json);为 out.write(json.getBytes());

原因为:out.writeBytes(json);该语句在转中文时候,已经变成乱码

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));
}
incCount(len);
}

因为java里的char类型是16位的,一个char可以存储一个中文字符,在将其转换为 byte后高8位会丢失,这样就无法将中文字符完整的输出到输出流中。所以在可能有中文字符输出的地方最好先将其转换为字节数组,然后再通过write写入流,

相关文章
|
8月前
|
应用服务中间件
tomcat服务器get、post请求及响应中文乱码问题
tomcat服务器get、post请求及响应中文乱码问题
|
8月前
|
前端开发 Java API
Android端通过HttpURLConnection上传文件到服务器
Android端通过HttpURLConnection上传文件到服务器
118 0
|
JSON API Apache
基于OkHttp网络通信工具类(发送get、post请求、文件上传和下载)
okhttp是专注于提升网络连接效率的http客户端。 优点: 1、它能实现同一ip和端口的请求重用一个socket,这种方式能大大降低网络连接的时间,和每次请求都建立socket,再断开socket的方式相比,降低了服务器服务器的压力。 2、okhttp 对http和https都有良好的支持。 3、okhttp 不用担心android版本变换的困扰。 4、成熟的网络请求解决方案,比HttpURLConnection更好用。 5、支持异步发送网络请求,响应可在线程处理。
|
Java
Java:HttpURLConnection发送GET和POST请求
Java:HttpURLConnection发送GET和POST请求
271 0
|
Web App开发 Java
Javaweb 响应字节流输出中文乱码问题
Javaweb 响应字节流输出中文乱码问题
387 0
Javaweb 响应字节流输出中文乱码问题
|
JavaScript 开发者
通过服务器端设置响应报文头来解决乱码问题|学习笔记
快速学习通过服务器端设置响应报文头来解决乱码问题
使用HttpURLConnection发送GE,POST请求
使用HttpURLConnection发送GE,POST请求和上传文件
143 0