zoukankan      html  css  js  c++  java
  • java httpUrlConnection 调用远程接口报400

    java httpUrlConnection 调用远程接口报400

    1.问题的出现:
    线下开发时候使用httpUrlConnction测试调用远程接口一点问题都没有,但是打包后放到线上去后出现400的错误同样的参数在线下可以调试,放在线上就不行了。

    分析
    一般报400说明接口接收到了错误的参数,由于是远程调用别人的服务器接口看不到那边的日志,我们这边只有一个400 ,信息提示说对面json解析错误。那么我们同样的参数为什么放在线上就会出问题,
    原因可能是我们的服务器的环境或者编码不对。
    
    解决的办法
    修改参数的编码,但是不管对json字符串怎么编码,都不管用,最后发现要再读入流的时候对参数进行编码才可以,编码的地方不对
    
    代码示例
    
        /**
         * 调用远程接口
         * @param url  接口的url路径
         * @param pamare  List的json数组
         * @return
         */
        public static String sendPost(String url, String pamare) {
    
            PrintWriter out = null;
            BufferedReader in = null;
            String result = "";
            try {
                // 打开和URL之间的连接
                HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                // 设置通用的请求属性
                conn.setRequestMethod("POST");
                conn.setConnectTimeout(4 * 1000);
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    
                // 发送POST请求必须设置如下两行
                conn.setDoOutput(true);
                conn.setDoInput(true);
                // 获取URLConnection对象对应的输出流
                out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
                out.println(pamare);
                // flush输出流的缓冲
                out.flush();
                InputStream is = null;
                if (conn.getResponseCode() >= 400) {
    
                    is = conn.getErrorStream();
                } else {
                    is = conn.getInputStream();
                }
    
                // 定义BufferedReader输入流来读取URL的响应
                in = new BufferedReader(new InputStreamReader(is,"utf-8"));
                String line;
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            } catch (Exception e) {
                System.out.println("发送 POST 请求出现异常!" + e);
                e.printStackTrace();
            }
            //使用finally块来关闭输出流、输入流
            finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            return result;
        }
    
    
    
  • 相关阅读:
    variant conversion error for variable:v8
    oracle第二步创建表空间、用户、授权
    Java WEB 乱码解决大全
    跳转的两种方式(转发与重定向)
    jsp页面中 <%%> <%! %>, <%=%> <%-- --%>有什么区别
    Web.xml中Filter过滤器标签几个说明
    SSH面试题(struts2+Spring+hibernate)
    做一个java项目要经过那些正规的步骤
    web.xml 配置中classpath: 与classpath*:的区别
    Web.xml配置详解之context-param
  • 原文地址:https://www.cnblogs.com/java-hardly-road/p/11283480.html
Copyright © 2011-2022 走看看