HttpClientUtil工具類

依賴

<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.11</version>
</dependency>
package com.example.http;

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

import org.apache.http.HttpEntity;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {
    // 編碼格式。發送編碼格式統一用UTF-8
    private static final String ENCODING = "UTF-8";

    // 設置連接超時時間,單位毫秒。
    private static final int CONNECT_TIMEOUT = 5000;

    // 請求獲取數據的超時時間(即響應時間),單位毫秒。
    private static final int SOCKET_TIMEOUT = 5000;

    /**
     * Description: get請求
     *
     * @param url 路徑
     * @return 響應結果
     */
    public static String get(String url) throws Exception {
        return get(url, null);
    }

    /**
     * Description: post請求
     *
     * @param url    路徑
     * @param params 參數
     * @return 響應結果
     */
    public static String post(String url, Map<String, Object> params) throws Exception {
        return post(url, params, null);
    }

    /**
     * Description: post請求(用於請求json格式的參數)
     *
     * @param url    路徑
     * @param params json參數
     * @return 響應結果
     */
    public static String jsonPost(String url, String params) throws Exception {
        return jsonPost(url, params, null);
    }

    /**
     * Description: get請求
     *
     * @param url     路徑
     * @param headers 請求頭信息
     * @return 響應結果
     */
    public static String get(String url, Map<String, String> headers) throws Exception {
        CloseableHttpClient httpClient = null;
        HttpGet httpGet;
        CloseableHttpResponse httpResponse = null;
        String result;
        try {
            httpClient = HttpClientBuilder.create().build();

            httpGet = new HttpGet(url);
            //設置請求頭
            setHeader(headers, httpGet);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpGet.setConfig(config);
            result = getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            release(httpResponse, httpClient);
        }
        return result;
    }


    /**
     * Description: post請求
     *
     * @param url     路徑
     * @param params  參數
     * @param headers 請求頭信息
     * @return 響應結果
     */
    public static String post(String url, Map<String, Object> params, Map<String, String> headers) throws Exception {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost;
        CloseableHttpResponse httpResponse = null;
        String result;
        try {
            httpClient = HttpClientBuilder.create().build();
            httpPost = new HttpPost(url);
            //設置請求頭
            setHeader(headers, httpPost);
            //設置參數
            setParam(params, httpPost);

            RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpPost.setConfig(config);

            result = getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            release(httpResponse, httpClient);
        }
        return result;
    }


    /**
     * Description: post請求(用於請求json格式的參數)
     *
     * @param url     路徑
     * @param params  json參數
     * @param headers 請求頭信息
     * @return 響應結果
     */
    public static String jsonPost(String url, String params, Map<String, String> headers) throws Exception {
        CloseableHttpClient httpClient = null;
        HttpPost httpPost;
        CloseableHttpResponse httpResponse = null;
        String result;
        try {
            httpClient = HttpClientBuilder.create().build();
            httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            //設置請求頭
            setHeader(headers, httpPost);
            //設置參數
            httpPost.setEntity(new StringEntity(params, ENCODING));
            RequestConfig config = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            httpPost.setConfig(config);

            result = getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            release(httpResponse, httpClient);
        }
        return result;
    }

    /**
     * Description: 封裝請求頭
     *
     * @param headers    請求頭
     * @param httpMethod httpMethod
     */
    public static void setHeader(Map<String, String> headers, HttpRequestBase httpMethod) {
        // 封裝請求頭
        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                httpMethod.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封裝請求參數
     *
     * @param params     請求參數
     * @param httpMethod httpMethod
     */
    public static void setParam(Map<String, Object> params, HttpEntityEnclosingRequestBase httpMethod) throws UnsupportedEncodingException {

        List<NameValuePair> list = new ArrayList<>();
        if (null != params) {
            for (Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue() != null ? entry.getValue().toString() : "";
                list.add(new BasicNameValuePair(key, value));
            }
        }
        if (list.size() > 0) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, ENCODING);
            httpMethod.setEntity(entity);
        }
    }

    /**
     * Description: 獲取響應結果
     *
     * @param httpResponse httpResponse
     * @param httpClient   httpClient
     * @param httpMethod   httpMethod
     * @return 響應結果
     * @throws Exception Exception
     */
    public static String getHttpClientResult(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        String result = null;
        // 執行請求
        httpResponse = httpClient.execute(httpMethod);

        // 獲取返回結果
        if (httpResponse != null) {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                result = EntityUtils.toString(resEntity, ENCODING);
            }
        }
        return result;
    }


    /**
     * Description: 釋放資源
     *
     * @param httpResponse HttpResponse
     * @param httpClient   HttpClient
     * @throws IOException IOException
     */
    public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

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