Java發送Http帶HEADER參數


直接上代碼:

說明: 如果返回狀態碼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;
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM