发送http请求,返回结果中文乱码问题

1年前 ⋅ 959 阅读

需要注意以下两点:

  • 1.设置请求属性编码为UTF-8:conn.setRequestProperty("Accept-Charset", "UTF-8");
  • 2.对输出结果进行UTF-8编码处理:out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
  • 参考代码如下:
public static String sendPostJson(String url, String param) {
        System.out.println(url + param);
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";

        try {
            SslUtils.ignoreSsl();
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out.write(param);
            out.flush();

            String line;
            for(in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8")); (line = in.readLine()) != null; result = result + line) {
            }
        } catch (Exception var16) {
            System.out.println("发送 POST 请求出现异常!" + var16);
            var16.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }

                if (in != null) {
                    in.close();
                }
            } catch (IOException var15) {
                var15.printStackTrace();
            }

        }

        return result;
    }

全部评论: 0

    我有话说: