HttpClientUtil類

package com.app.util;
import java.io.IOException;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 封裝了一些採用HttpClient發送HTTP請求的方法
 *
 */
@Slf4j
public class HttpClientUtil {


    private static RequestConfig requestConfig = null;

    static {
        // 設置請求和傳輸超時時間
        requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
    }

    /**
     * post請求傳輸json參數
     *
     * @param url
     *            url地址
     * @param jsonParam
     *            參數
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        // post請求返回結果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 設置請求和傳輸超時時間
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解決中文亂碼問題
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 請求發送成功,並得到響應
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 讀取服務器返回過來的json字符串數據
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串轉換成json對象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post請求提交失敗:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post請求提交失敗:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post請求傳輸json參數
     *
     * @param url
     *            url地址
     * @param map
     *            參數
     * @return
     */
    public static JSONObject httpPost(String url, Map map) {
        // post請求返回結果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 設置請求和傳輸超時時間
        httpPost.setConfig(requestConfig);
        try {
            if (null != map) {
                // 解決中文亂碼問題
                StringEntity entity = new StringEntity(map.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 請求發送成功,並得到響應
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 讀取服務器返回過來的json字符串數據
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串轉換成json對象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post請求提交失敗:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post請求提交失敗:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post請求傳輸String參數 例如:name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url
     *            url地址
     * @param strParam
     *            參數
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) {
        // post請求返回結果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != strParam) {
                // 解決中文亂碼問題
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 請求發送成功,並得到響應
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 讀取服務器返回過來的json字符串數據
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串轉換成json對象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post請求提交失敗:" + url, e);
                }
            }
        } catch (IOException e) {
            log.error("post請求提交失敗:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 發送get請求
     *
     * @param url
     *            路徑
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get請求返回結果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 發送get請求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 請求發送成功,並得到響應
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 讀取服務器返回過來的json字符串數據
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串轉換成json對象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                log.error("get請求提交失敗:" + url);
            }
        } catch (IOException e) {
            log.error("get請求提交失敗:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

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