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

 

转自:http://blog.csdn.net/hwj3747/article/details/53635539

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);

解决。

posted @ 2017-07-12 15:39  我不会游泳  阅读(11504)  评论(0编辑  收藏  举报