Java HttpURLConnection模拟请求Rest接口解决中文乱码问题

说明

在java使用HttpURLConnection请求rest接口的时候出现了POST请求出现中文乱码的问题,经过把传入的String通过多种方法进行编码发现都解决不了,如下:

  String teString=new String("你好".getBytes("ISO-8859-1"),"UTF-8");

网上HttpURLConnection的请求通常是这样子的:

    public static String PostRequest(String URL,String obj) { 
        String jsonString="";
        try { 
            //创建连接 
            URL url = new URL(URL); 
            HttpURLConnection connection = (HttpURLConnection) url 
                    .openConnection(); 
            connection.setDoOutput(true); 
            connection.setDoInput(true); 
            connection.setRequestMethod("POST"); //设置请求方法
            connection.setRequestProperty("Charsert", "UTF-8"); //设置请求编码
            connection.setUseCaches(false); 
            connection.setInstanceFollowRedirects(true); 
            connection.setRequestProperty("Content-Type", 
                    "application/json"); 

            connection.connect(); 

            //POST请求 
            DataOutputStream out = new DataOutputStream( 
                    connection.getOutputStream()); //关键的一步


            out.writeBytes(obj); 
            out.flush(); 
            out.close(); 

            // 读取响应
            if (connection.getResponseCode()==200) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                jsonString=sb.toString();
                reader.close();
            }//返回值为200输出正确的响应信息

            if (connection.getResponseCode()==400) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                String lines;
                StringBuffer sb = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sb.append(lines);
                }
                jsonString=sb.toString();
                reader.close();
            }//返回值错误,输出错误的返回信息
            // 断开连接 
            connection.disconnect(); 
        } catch (MalformedURLException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (UnsupportedEncodingException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        return jsonString;
    } 

需要注意的是返回值为200时,connection.getInputStream()才有值,返回值为400时connection.getInputStream()是空的,connection.getErrorStream()才有值。

以上是大多数网上博客文章的写法,但是我用这种方法遇到了中文乱码的问题。在out.writeBytes(obj);这一步无论对obj这个字符串怎样转换,得到的结果还是乱码,最终得到的解决方法是这样的:
把这个部分代码,

 DataOutputStream out = new DataOutputStream( 
                    connection.getOutputStream()); //关键的一步
            out.writeBytes(obj); 

改成:

 PrintWriter out = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(),"utf-8"));  
            out.println(obj);

这样问题就解决了!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值