常用http请求发送接收方无法接收到请求参数原因

今天与企查查进行联调,发现一个特殊的情况,我用之前调用的工具类,调用老是报参数为空,很神奇,我之前这个工具类用过很多项目,按道理是不会出现这样的情况。

然后我换了三四个工具类去进行调用,直到找到下面这个工具类才通,在拦截错误的时候 ,需要进行区分400错误 还是服务器错误,不然抛出不了有用信息。

public static StringsendHttpsPost(String url, String requestJson, String token) {

// 构建请求参数

    String result ="";

    PrintWriter out =null;

    BufferedReader in =null;

    log.info("请求地址:" + url);

    log.info("请求参数:" + requestJson);

    try {

trustAllHosts();

        URL url2 =new URL(url);

        HttpsURLConnection urlCon = (HttpsURLConnection) url2.openConnection();

        urlCon.setHostnameVerifier(DO_NOT_VERIFY);

        urlCon.setDoOutput(true);

        urlCon.setDoInput(true);

        urlCon.setRequestMethod("POST");

        urlCon.setRequestProperty("Content-type", "application/json;charset=UTF-8");

        if (!StringUtils.isEmpty(token)) {

urlCon.setRequestProperty("Authorization", token);

        }

// 发送POST请求必须设置如下两行

        urlCon.setDoOutput(true);

        urlCon.setDoInput(true);

        // 获取URLConnection对象对应的输出流

        OutputStream os = urlCon.getOutputStream();

        //参数是键值队  , 不以"?"开始

        os.write(requestJson.getBytes());

        os.flush();

        int responseCode = urlCon.getResponseCode();

        if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {

// 发送请求参数

            // 定义BufferedReader输入流来读取URL的响应

            in =new BufferedReader(

new InputStreamReader(urlCon.getInputStream()));

            String line;

            while ((line = in.readLine()) !=null) {

result += line;

            }

}else {

// 发送请求参数

            // 定义BufferedReader输入流来读取URL的响应

            in =new BufferedReader(

new InputStreamReader(urlCon.getErrorStream()));

            String line;

            while ((line = in.readLine()) !=null) {

result += line;

            }

if (!StringUtils.isEmpty(result)) {

JSONObject jsonObject = JSON.parseObject(result);

                String message = jsonObject.getString("message");

                if (StringUtils.isEmpty(message)){

message = jsonObject.getString("error");

                }

throw new BadRequestAlertException(message);

            }

}

}catch (IOException e) {

e.printStackTrace();

        throw new BadRequestAlertException("解析数据异常");

    }finally {// 使用finally块来关闭输出流、输入流

        try {

if (in !=null) {

in.close();

            }

}catch (IOException ex) {

ex.printStackTrace();

        }

}

return result;

}

你可能感兴趣的:(常用http请求发送接收方无法接收到请求参数原因)