关于HttpURLConnection推送数据出现中文乱码问题。

       在使用HttpURLConnection访问其他系统接口推送数据时出现了中文乱码问题,使用OutputStream 推送字节流,对方系统解析中文出现乱码,无法通过校验,改用PrintWriter推送字符流,成功解析!~贴代码记录一下!!~

        

        // 接口参数
        Map<String, Object> param = new HashMap<String, Object>();
        //接口地址
        String url = "";
        URL postUrl = new URL(url);
        //跳过证书校验
        if("https".equalsIgnoreCase(postUrl.getProtocol())){
            SslUtils.ignoreSsl();
        }
        HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("Charset", "UTF-8");
        connection.setConnectTimeout(100000);
        connection.setReadTimeout(100000);

        connection.setRequestMethod("POST");
        //这里是使用form形式推送的数据,json同理
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        //OutputStream out = connection.getOutputStream(); 方法1

        PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8"));//方法2

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            sb.append(entry.getKey() + "=" + entry.getValue());
            sb.append("&");
        }
        String sb1 = sb.toString();
        if (sb1.endsWith("&")) {
            sb1 = sb1.substring(0, sb1.length() - 1);
        }
        //out.write(sb1.toString().getBytes()); 方法1
        out.write(sb1.toString());//方法2

        out.flush();
        out.close();

        

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值