Java | POST请求,响应中文乱码处理

版权声明:喜欢的点个赞吧!欢迎转载,请注明出处来源,博文地址: https://blog.csdn.net/u012294515/article/details/84617140

起因

中文乱码是老生常谈的问题了,在post请求中经常发现请求体或者返回值中文乱码问题,且在header中设置了UTF-8也仍然无法解决。

代码示例

package com.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * rest接口调用类
 * sunxy
 * @author Sunxy 
 * Create By 2018-11-23 下午04:21:12
 */
public class RestUtil {
    private static final Log logger = LogFactory.getLog(RestUtil.class);

    /**
     * post请求
     */
    public static String sendPost(String restUrl, String param) {
        String result = "";
        int responseCode;
        HttpURLConnection conn = null;
        try {
            // 打开URL
            StringBuilder sbURL = new StringBuilder(restUrl);
            URL url = new URL(sbURL.toString());
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 请求体参数设置
            //System.out.println("request param:" + param);
            // 加入请求体
            conn.setDoOutput(true);
            //输入流
            OutputStream os = conn.getOutputStream();
            os.write(param);
            os.flush();
            // 输出response code
            responseCode = conn.getResponseCode();
            // 输出response
            if(responseCode == 200){
                //输出流
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream());
                result = reader.readLine();
            }else{
                result="false";
            }
            // 断开连接
            conn.disconnect();
        } catch (Exception e) {
            result="false";
            conn.disconnect();
            logger.error("post请求提交失败:" + restUrl, e);
        }
        return result;
    }

}

解决方案:

在以代码中修改,将输入流转UTF-8,输出流转UFT-8

 //输入流
 //OutputStream os = conn.getOutputStream();
 OutputStreamWriter  os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//输出流
//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));

猜你喜欢

转载自blog.csdn.net/u012294515/article/details/84617140