首页 > 技术文章 > Java发送Http带HEADER参数

coloz 2020-06-02 14:46 原文

直接上代码:

说明: 如果返回状态码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;
        }
    }

 

推荐阅读