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

    解决。

  • 相关阅读:
    图标字体IcoMoon 使用
    JS 寻找孩子并打印路径
    为什么要用on()而不直接使用click
    setTimeout 虚假的“异步”
    解决Ajax.BeginForm还是刷新页面的问题
    .net生成Excel,并下载
    C#判断文件是否正在被使用
    sql为数字添加千分位(也就是钱的格式)
    HotelIInventory项目小结
    一步一步实现FormsAuthentic验证登录
  • 原文地址:https://www.cnblogs.com/antis/p/7155810.html
Copyright © 2020-2023  润新知