HttpURLConnection以及GBK转UTF-8中文部分乱码问题

调用例子1的方法,返回的数据时而是正常的中文,时而最后一位中文是以“??”为标志的乱码。

发送post请求的接口已设置filer:encoding=UTF-8,且工作空间字符集设置为UTF-8。

例子1:

public static String test(String path, String param) throws Exception {

        URL url = new URL(path);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.connect();

        DataOutputStream out = new DataOutputStream( conn.getOutputStream());
        out.writeBytes(param);
        out.flush();
        out.close();
        BufferedReader bfReader= new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String lines;
        StringBuffer sb = new StringBuffer();
        while ((lines = bfReader.readLine()) != null) {
            lines = new String(lines.getBytes(), "UTF-8");
            sb.append(lines);
        }
        bfReader.close();

        // 断开连接
        conn.disconnect();
        return sb.toString();

    }



查其现象,发现当中文字数为偶数时,不出现乱码;中文字数为奇数时,最后一位中文出现乱码。

仔细测试后,确认是GBK转UTF-8时出现的部分乱码问题(两种方式的汉字字节数不统一造成的)。
但服务接口返回内容是以UTF-8格式发送的,接收时怎么会出现GBK格式?
继续深究,发现HttpURLConnection 接收返回内容时没有设置字符集,此时使用默认字符集GBK,即

BufferedReader bfReader= new BufferedReader(new InputStreamReader(conn.getInputStream())),

为默认字符集接收。

继续执行到 lines = new String(lines.getBytes(), "UTF-8")这一行,便出现了奇偶数部分乱码的情况。

例子2为修改后的方法:

public static String test(String path, String param) throws Exception {

        URL url = new URL(path);
        HttpURLConnection conn= (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setInstanceFollowRedirects(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.connect();

        DataOutputStream out = new DataOutputStream( conn.getOutputStream());
        out.writeBytes(param);
        out.flush();
        out.close();
        BufferedReader bfReader= new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        String lines;
        StringBuffer sb = new StringBuffer();
        while ((lines = bfReader.readLine()) != null) {

            // utf-8 无需再次转码

            //lines = new String(lines.getBytes(), "UTF-8");
            sb.append(lines);
        }
        bfReader.close();

        // 断开连接
        conn.disconnect();
        return sb.toString();

    }

此时已无需再次转码,成功接收!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值