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