HttpClientUtil 封裝 apache.httpcomponents 4.5.8

HttpClientUtil 封裝 apache.httpcomponents 4.5.8

注意:本篇博客風格(不多比比就是擼代碼!!!)

GitHub: link. 歡迎star

一、maven依賴

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.8</version>
        </dependency>

二、HttpClientUtil.java

import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Andon
 * @date 2019/4/3
 */
@SuppressWarnings("Duplicates")
public class HttpClientUtil {

    // 編碼格式,發送編碼格式統一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 設置連接超時時間,單位毫秒
    private static final int CONNECT_TIMEOUT = 10 * 60 * 1000;

    // 請求響應超時時間,單位毫秒
    private static final int SOCKET_TIMEOUT = 10 * 60 * 1000;

    /**
     * 發送get請求;帶請求頭和請求參數
     */
    public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 創建httpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 創建訪問地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (!ObjectUtils.isEmpty(params)) {
            params.forEach(uriBuilder::setParameter);
        }

        // 創建http對象
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 設置請求超時時間及響應超時時間
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);

        // 設置請求頭
        packageHeader(headers, httpGet);

        // 執行請求獲取響應體並釋放資源
        return getHttpClientResult(httpClient, httpGet);
    }

    /**
     * 發送get請求;帶請求參數
     */
    public static String doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * 發送get請求;不帶請求頭和請求參數
     */
    public static String doGet(String url) throws Exception {
        return doGet(url, null, null);
    }

    /**
     * 發送post請求;帶請求頭和請求參數
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        // 創建httpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 創建http對象
        HttpPost httpPost = new HttpPost(url);

        // 設置請求超時時間及響應超時時間
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);

        // 設置請求頭
        /*httpPost.setHeader("Cookie", "");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
        httpPost.setHeader("Accept-Encoding", "gzip, deflate, br");
        httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");*/
        // 設置請求頭
        packageHeader(headers, httpPost);

        // 封裝請求參數
        packageParam(params, httpPost);

        // 執行請求獲取響應體並釋放資源
        return getHttpClientResult(httpClient, httpPost);
    }

    /**
     * 發送post請求;帶請求參數
     */
    public static String doPost(String url, Map<String, String> params) throws IOException {
        return doPost(url, null, params);
    }

    /**
     * 發送post請求;不帶請求頭和請求參數
     */
    public static String doPost(String url) throws IOException {
        return doPost(url, null, null);
    }

    /**
     * 發送put請求;帶請求頭和請求參數
     */
    public static String doPut(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPut.setConfig(requestConfig);
        packageHeader(headers, httpPut);
        packageParam(params, httpPut);
        return getHttpClientResult(httpClient, httpPut);
    }

    /**
     * 發送put請求;帶請求參數
     */
    public static String doPut(String url, Map<String, String> params) throws IOException {
        return doPut(url, null, params);
    }

    /**
     * 發送put請求;不帶請求頭和請求參數
     */
    public static String doPut(String url) throws IOException {
        return doPut(url, null, null);
    }

    /**
     * 發送delete請求;帶請求頭
     */
    public static String doDelete(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(url);
        if (!ObjectUtils.isEmpty(params)) {
            params.forEach(uriBuilder::setParameter);
        }
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpDelete.setConfig(requestConfig);
        packageHeader(headers, httpDelete);
        return getHttpClientResult(httpClient, httpDelete);
    }

    /**
     * 發送delete請求;帶請求參數
     */
    public static String doDelete(String url, Map<String, String> params) throws Exception {
        return doDelete(url, null, params);
    }

    /**
     * 發送delete請求;不帶請求頭和請求參數
     */
    public static String doDelete(String url) throws Exception {
        return doDelete(url, null, null);
    }

    /**
     * 設置請求頭
     */
    private static void packageHeader(Map<String, String> headers, HttpRequestBase httpMethod) {
        if (!ObjectUtils.isEmpty(headers)) {
            headers.forEach(httpMethod::setHeader);
        }
    }

    /**
     * 封裝請求參數
     */
    private static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException {
        if (!ObjectUtils.isEmpty(params)) {
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            params.forEach((key, value) -> nameValuePairs.add(new BasicNameValuePair(key, value)));
            httpMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, ENCODING));
        }
    }

    /**
     * 執行請求獲取響應體並釋放資源
     */
    private static String getHttpClientResult(CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws IOException {
        // 執行請求
        CloseableHttpResponse httpResponse = null;
        try {
            // 獲取響應體
            httpResponse = httpClient.execute(httpMethod);
            String content = "";
            if (!ObjectUtils.isEmpty(httpResponse) && !ObjectUtils.isEmpty(httpResponse.getEntity())) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return content;
        } finally {
            // 釋放資源
            if (!ObjectUtils.isEmpty(httpResponse)) {
                httpResponse.close();
            }
            if (!ObjectUtils.isEmpty(httpClient)) {
                httpClient.close();
            }
        }
    }
}

GitHub: link. 歡迎star

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章