java傳送http請求

邢帅杰發表於2024-07-19
pom
<dependency>
  <groupId>org.apache.httpcomponents.client5</groupId>
  <artifactId>httpclient5</artifactId>
  <version>5.1.3</version>
</dependency>

package com.xcg.webapp.Common;

import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.zip.GZIPOutputStream;

/**
 * https://blog.csdn.net/HIGK_365/article/details/136985075
 */
public final class HttpRestUtil {
    //設定字元編碼
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * 傳送HTTP POST請求,引數為JSON格式。
     * 此方法用於將JSON格式的字串作為請求體傳送到指定的URL,並接收響應。
     *
     * @param url        請求的URL地址。不能為空。
     * @param jsonData   請求的引數,應為符合JSON格式的字串。
     * @param headParams 請求的頭部引數,以鍵值對形式提供。可以為空,但如果非空,則新增到請求頭中。
     * @return 伺服器響應的字串形式內容。如果請求失敗,則可能返回null。
     * throws BusinessException 當發生不支援的編碼、客戶端協議錯誤或IO異常時丟擲。
     */
    public static String post(String url, String jsonData, Map<String, String> headParams) throws Exception {
        String result = null;
        // 建立HTTP客戶端例項
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;

        try {
            // 建立HTTP POST請求物件
            HttpPost httpPost = new HttpPost(url);
            // 配置請求和傳輸超時時間
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(100, TimeUnit.SECONDS)
                    .build();
            httpPost.setConfig(requestConfig);
            // 將JSON字串引數轉換為StringEntity,並設定請求實體
            httpPost.setEntity(new StringEntity(jsonData, ContentType.create("application/json", CHARSET_UTF8)));
            // 如果存在頭部引數,則新增到請求頭中
            if (headParams != null && !headParams.isEmpty()) {
                for (Map.Entry<String, String> entry : headParams.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 執行請求並獲取響應
            response = httpClient.execute(httpPost);
            // 檢查響應狀態碼
            int statusCode = response.getCode();
            if (HttpStatus.SC_OK != statusCode) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            // 從響應中獲取內容並轉換為字串
            var entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, CHARSET_UTF8);
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            release(response, httpClient);
        }
        return result;
    }

    /**
     * get請求
     * https://blog.csdn.net/Barry_Li1949/article/details/134641891
     */
    public static String get(String urlWithParams) throws Exception {
        return get(urlWithParams, null, null);
    }

    public static String get(String url, Map<String, String> params, Map<String, String> headParams) throws Exception {
        String result = null;
        // 建立HTTP客戶端例項
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String paramStr = null;
        try {
            // 構建請求引數列表
            List<BasicNameValuePair> paramsList = new ArrayList<>();
            if (params != null) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    paramsList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                // 將引數列表轉換為字串形式,用於拼接到URL後
                paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramsList));
            }
            // 拼接引數到URL
            StringBuffer sb = new StringBuffer();
            sb.append(url);
            if (!StringUtils.isBlank(paramStr)) {
                sb.append("?");
                sb.append(paramStr);
            }
            // 建立HTTP GET請求物件
            HttpGet httpGet = new HttpGet(sb.toString());
            // 配置請求和傳輸超時時間
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(100, TimeUnit.SECONDS)
                    .build();
            httpGet.setConfig(requestConfig);
            // 如果存在頭部引數,則新增到請求頭中
            if (headParams != null && !headParams.isEmpty()) {
                for (Map.Entry<String, String> entry : headParams.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 執行請求並獲取響應
            response = httpClient.execute(httpGet);
            // 檢查響應狀態碼
            int statusCode = response.getCode();
            if (HttpStatus.SC_OK != statusCode) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            // 從響應中獲取內容並轉換為字串
            var entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, CHARSET_UTF8);
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //釋放資源
            release(response, httpClient);
        }
        return result;
    }

    /**
     * 釋放資源,httpResponse為響應流,httpClient為請求客戶端
     */
    private static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

相關文章