首页 > 编程语言 > 详细

Java发送Http带HEADER参数

时间:2020-06-02 17:42:11      阅读:317      评论:0      收藏:0      [点我收藏+]

直接上代码:

说明: 如果返回状态码200表示调用成功; 其他情况都返回null表示失败;

  /**
     * post with  json  and  head params
     *
     * @param url
     * @param headsMap
     * @param json
     * @return {@code  not null(maybe ""),statusCode=200(success) } {@code  null (fail)}
     */
    public static String httpPostWithJsonAndHeader(String url, String json, Map<String, String> headsMap) {
        String result = "";
        log.info("本次请求地址:{} ", url);
        log.info("本次传递数据:{}", json);

        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(json, "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        //
        if (headsMap != null && !headsMap.isEmpty()) {
            headsMap.forEach((key, value) -> {
                httpPost.addHeader(key, value);
            });
        }
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse response = httpClient.execute(httpPost)) {

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                log.info("HTTP请求成功!");

                // 从响应模型中获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    result = EntityUtils.toString(responseEntity);
                }

            } else {
                log.info("HTTP请求失败!");
                return null;
            }

            log.info("返回结果:{}", result);
            return result;
        } catch (Exception e) {
            log.error("HTTP请求出现异常4:", e);
            return null;
        }
    }

 

Java发送Http带HEADER参数

原文:https://www.cnblogs.com/coloz/p/13031148.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!