02HttpClient工具類

import java.io.Serializable;

/**
 * @Description: <p> HttpClientResult  </p>
 * @Author: - Jason
 * @CreatTime:2019/7/24 - 17:57
 * @Modify By:
 * @ModifyTime: 2019/7/24
 * @Modify marker:
 */
public class HttpClientResult implements Serializable {

    /**
     * 響應(yīng)狀態(tài)碼
     */
    private int code;

    /**
     * 響應(yīng)數(shù)據(jù)
     */
    private String content;


    public HttpClientResult(int code) {
        this.code = code;
    }

    public HttpClientResult(int code, String content) {
        this.code = code;
        this.content = content;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}
import org.apache.commons.httpclient.HttpStatus;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
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 java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description: <p> HttpClientUtils  </p>
 * @Author: - Jason
 * @CreatTime:2019/7/24 - 17:42
 * @Modify By:
 * @ModifyTime: 2019/7/24
 * @Modify marker:
 */
public class HttpClientUtils {

    /**
     * 編碼格式。發(fā)送編碼格式統(tǒng)一用UTF-8
     */
    private static final String ENCODING = "UTF-8";

    /**
     * 設(shè)置連接超時(shí)時(shí)間走触,單位毫秒。
     */
    private static final int CONNECT_TIMEOUT = 6000;

    /**
     * 請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間)形导,單位毫秒。
     */
    private static final int SOCKET_TIMEOUT = 6000;


    /**
     * 發(fā)送get請(qǐng)求榛了;不帶請(qǐng)求頭和請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url) throws Exception {
        return doGet(url, null, null);
    }


    /**
     * 發(fā)送get請(qǐng)求凡桥;帶請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @param params 請(qǐng)求參數(shù)集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, null, params);
    }

    /**
     * 發(fā)送get請(qǐng)求;帶請(qǐng)求頭和請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @param headers  請(qǐng)求頭集合
     * @param params 請(qǐng)求參數(shù)集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doGet(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 創(chuàng)建httpClient對(duì)象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 創(chuàng)建訪問(wèn)的地址
        URIBuilder uriBuilder = new URIBuilder(url);
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        // 創(chuàng)建http對(duì)象
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        /**
         * setConnectTimeout:設(shè)置連接超時(shí)時(shí)間僵闯,單位毫秒。
         * setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection
         * 超時(shí)時(shí)間藤滥,單位毫秒鳖粟。這個(gè)屬性是新加的屬性,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的拙绊。
         * setSocketTimeout:請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間)向图,單位毫秒。 如果訪問(wèn)一個(gè)接口标沪,多少時(shí)間內(nèi)無(wú)法返回?cái)?shù)據(jù)榄攀,就直接放棄此次調(diào)用。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpGet.setConfig(requestConfig);
        // 設(shè)置請(qǐng)求頭
        packageHeader(headers, httpGet);
        // 創(chuàng)建httpResponse對(duì)象
        CloseableHttpResponse httpResponse = null;
        try {
            // 執(zhí)行請(qǐng)求并獲得響應(yīng)結(jié)果
            return getHttpClientResult(httpResponse, httpClient, httpGet);
        } finally {
            // 釋放資源
            release(httpResponse, httpClient);
        }
    }

    /**
     * 發(fā)送post請(qǐng)求金句;不帶請(qǐng)求頭和請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url) throws Exception {
        return doPost(url, null, null);
    }

    /**
     * 發(fā)送post請(qǐng)求檩赢;帶請(qǐng)求參數(shù)
     *
     * @param url 請(qǐng)求地址
     * @param params 參數(shù)集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, null, params);
    }

    /**
     * 發(fā)送post請(qǐng)求;帶請(qǐng)求頭和請(qǐng)求參數(shù)
     *
     * @param url 請(qǐng)求地址
     * @param headers 請(qǐng)求頭集合
     * @param params 請(qǐng)求參數(shù)集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPost(String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 創(chuàng)建httpClient對(duì)象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 創(chuàng)建http對(duì)象
        HttpPost httpPost = new HttpPost(url);
        /**
         * setConnectTimeout:設(shè)置連接超時(shí)時(shí)間违寞,單位毫秒贞瞒。
         * setConnectionRequestTimeout:設(shè)置從connect Manager(連接池)獲取Connection
         * 超時(shí)時(shí)間,單位毫秒趁曼。這個(gè)屬性是新加的屬性军浆,因?yàn)槟壳鞍姹臼强梢怨蚕磉B接池的。
         * setSocketTimeout:請(qǐng)求獲取數(shù)據(jù)的超時(shí)時(shí)間(即響應(yīng)時(shí)間)挡闰,單位毫秒乒融。 如果訪問(wèn)一個(gè)接口,多少時(shí)間內(nèi)無(wú)法返回?cái)?shù)據(jù)摄悯,就直接放棄此次調(diào)用赞季。
         */
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPost.setConfig(requestConfig);
        // 設(shè)置請(qǐng)求頭
        httpPost.setHeader("Cookie", "");
        httpPost.setHeader("Connection", "keep-alive");
        httpPost.setHeader("Accept","application/json, text/plain, */*");
        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");
        httpPost.setHeader("Content type","application/json");
        packageHeader(headers, httpPost);
        // 封裝請(qǐng)求參數(shù)
        packageParam(params, httpPost);
        // 創(chuàng)建httpResponse對(duì)象
        CloseableHttpResponse httpResponse = null;
        try {
            // 執(zhí)行請(qǐng)求并獲得響應(yīng)結(jié)果
            return getHttpClientResult(httpResponse, httpClient, httpPost);
        } finally {
            // 釋放資源
            release(httpResponse, httpClient);
        }
    }


    /**
     * post請(qǐng)求通過(guò)jsonStr
     * @param url
     * @param reqJson
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPostJson(String url, String reqJson) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        httpPost.setHeader("HTTP Method","POST");
        httpPost.setHeader("Connection","Keep-Alive");
        httpPost.setHeader("Content-Type","application/json;charset=utf-8");
        StringEntity entity = new StringEntity(reqJson);
        entity.setContentType("application/json;charset=utf-8");
        httpPost.setEntity(entity);
        try {
            response = httpClient.execute(httpPost);
            return getHttpClientResult(response, httpClient, httpPost);
        } finally {
            release(response, httpClient);
        }
    }


    /**
     * 發(fā)送put請(qǐng)求;不帶請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url) throws Exception {
        return doPut(url);
    }

    /**
     * 發(fā)送put請(qǐng)求射众;帶請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @param params 參數(shù)集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doPut(String url, Map<String, String> params) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpPut.setConfig(requestConfig);
        packageParam(params, httpPut);
        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpPut);
        } finally {
            release(httpResponse, httpClient);
        }
    }

    /**
     * 發(fā)送delete請(qǐng)求碟摆;不帶請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpDelete httpDelete = new HttpDelete(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
        httpDelete.setConfig(requestConfig);
        CloseableHttpResponse httpResponse = null;
        try {
            return getHttpClientResult(httpResponse, httpClient, httpDelete);
        } finally {
            release(httpResponse, httpClient);
        }
    }


    /**
     * 發(fā)送delete請(qǐng)求晃财;帶請(qǐng)求參數(shù)
     * @param url 請(qǐng)求地址
     * @param params  參數(shù)集合
     * @return
     * @throws Exception
     */
    public static HttpClientResult doDelete(String url, Map<String, String> params) throws Exception {
        if (params == null) {
            params = new HashMap<String, String>();
        }

        params.put("_method", "delete");
        return doPost(url, params);
    }

    /**
     * Description: 封裝請(qǐng)求頭
     * @param params
     * @param httpMethod
     */
    public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
        // 封裝請(qǐng)求頭
        if (params != null) {
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                // 設(shè)置到請(qǐng)求頭到HttpRequestBase對(duì)象中
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
    }

    /**
     * Description: 封裝請(qǐng)求參數(shù)
     *
     * @param params
     * @param httpMethod
     * @throws UnsupportedEncodingException
     */
    public static void packageParam(Map<String, String> params, HttpEntityEnclosingRequestBase httpMethod)
            throws UnsupportedEncodingException {
        // 封裝請(qǐng)求參數(shù)
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            // 設(shè)置到請(qǐng)求的http對(duì)象中
            httpMethod.setEntity(new UrlEncodedFormEntity(nvps, ENCODING));
        }
    }

    /**
     * 獲得響應(yīng)結(jié)果
     * @param httpResponse
     * @param httpClient
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static HttpClientResult getHttpClientResult(CloseableHttpResponse httpResponse,
                                                       CloseableHttpClient httpClient, HttpRequestBase httpMethod) throws Exception {
        // 執(zhí)行請(qǐng)求
        httpResponse = httpClient.execute(httpMethod);
        // 獲取返回結(jié)果
        if (httpResponse != null && httpResponse.getStatusLine() != null) {
            String content = "";
            if (httpResponse.getEntity() != null) {
                content = EntityUtils.toString(httpResponse.getEntity(), ENCODING);
            }
            return new HttpClientResult(httpResponse.getStatusLine().getStatusCode(), content);
        }
        return new HttpClientResult(HttpStatus.SC_INTERNAL_SERVER_ERROR);
    }

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

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末叨橱,一起剝皮案震驚了整個(gè)濱河市典蜕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌罗洗,老刑警劉巖愉舔,帶你破解...
    沈念sama閱讀 218,386評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異伙菜,居然都是意外死亡轩缤,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)贩绕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)火的,“玉大人,你說(shuō)我怎么就攤上這事淑倾×蠛祝” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,704評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵娇哆,是天一觀的道長(zhǎng)湃累。 經(jīng)常有香客問(wèn)我,道長(zhǎng)碍讨,這世上最難降的妖魔是什么治力? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,702評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮勃黍,結(jié)果婚禮上宵统,老公的妹妹穿的比我還像新娘。我一直安慰自己覆获,他們只是感情好榜田,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著锻梳,像睡著了一般箭券。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上疑枯,一...
    開(kāi)封第一講書(shū)人閱讀 51,573評(píng)論 1 305
  • 那天辩块,我揣著相機(jī)與錄音,去河邊找鬼荆永。 笑死废亭,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的具钥。 我是一名探鬼主播豆村,決...
    沈念sama閱讀 40,314評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼骂删!你這毒婦竟也來(lái)了掌动?” 一聲冷哼從身側(cè)響起四啰,我...
    開(kāi)封第一講書(shū)人閱讀 39,230評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎粗恢,沒(méi)想到半個(gè)月后柑晒,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡眷射,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評(píng)論 3 336
  • 正文 我和宋清朗相戀三年匙赞,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片妖碉。...
    茶點(diǎn)故事閱讀 39,991評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡涌庭,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出欧宜,到底是詐尸還是另有隱情脾猛,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評(píng)論 5 346
  • 正文 年R本政府宣布鱼鸠,位于F島的核電站猛拴,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏蚀狰。R本人自食惡果不足惜愉昆,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望麻蹋。 院中可真熱鬧跛溉,春花似錦、人聲如沸扮授。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,910評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)刹勃。三九已至堪侯,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間荔仁,已是汗流浹背伍宦。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,038評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留乏梁,地道東北人次洼。 一個(gè)月前我還...
    沈念sama閱讀 48,158評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像遇骑,于是被迫代替她去往敵國(guó)和親卖毁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評(píng)論 2 355