001—spring整合httpclient4.5.2

1.添加pom依賴

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

spring與httpclient的配置

2.spring-httpclient.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--定義連接管理器 -->
    <bean id="connectionManager"
        class="org.apache.http.impl.conn.PoolingHttpClientConnectionManager"
        destroy-method="close">
        <!-- 最大連接數(shù) -->
        <property name="maxTotal" value="${http.maxTotal}" />
        <!--設(shè)置每個主機最大的并發(fā)數(shù) -->
        <property name="defaultMaxPerRoute" value="${http.defaultMaxPerRoute}" />
    </bean>

    <!--定義HttpClient構(gòu)建器 -->
    <bean id="httpClientBuilder" class="org.apache.http.impl.client.HttpClientBuilder"
        factory-method="create">
        <property name="connectionManager" ref="connectionManager" />
    </bean>

    <!--定義httpClient對象不傅,該bean一定是多例的 -->
    <bean id="httpClient" class="org.apache.http.impl.client.CloseableHttpClient"
        factory-bean="httpClientBuilder" factory-method="build" scope="prototype"></bean>
    <!--定義requestConfig構(gòu)建器 -->
    <bean id="requestConfigBuilder" class="org.apache.http.client.config.RequestConfig.Builder">
        <!--設(shè)置創(chuàng)建連接的最長時間 -->
        <property name="connectTimeout" value="${http.connectTimeout}" />
        <!--從連接池中獲取到連接的最長時間 -->
        <property name="connectionRequestTimeout" value="${http.connectionRequestTimeout}" />
        <!--數(shù)據(jù)傳輸?shù)淖铋L時間 -->
        <property name="socketTimeout" value="${http.socketTimeout}" />
    </bean>
    <!--請求參數(shù)對象 -->
    <bean class="org.apache.http.client.config.RequestConfig"
        factory-bean="requestConfigBuilder" factory-method="build"></bean>
    <!--定期清理無效連接 -->
    <bean class="org.apache.http.impl.client.IdleConnectionEvictor"
        destroy-method="shutdown">
        <constructor-arg index="0" ref="connectionManager" />
        <constructor-arg index="1" value="${http.maxIdleTime}" />
        <constructor-arg index="2" value="MINUTES" />
    </bean>
</beans>

3.httpclient.properties(httpclient的屬性)

#設(shè)置連接總數(shù)
http.maxTotal=500
#設(shè)置每個主機最大的并發(fā)數(shù)
http.defaultMaxPerRoute=100
#設(shè)置創(chuàng)建連接的最長時間
http.connectTimeout=2000
#從連接池中獲取到連接的最長時間
http.connectionRequestTimeout=500
#數(shù)據(jù)傳輸?shù)淖铋L時間
http.socketTimeout=6000
#空閑時間(用于定期清理空閑連接)
http.maxIdleTime = 1

4.HttpClientService(httpclient請求服務(wù))

package com.dowin.httpclient;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

/**
* @ClassName: HttpClientService
* @Description: HttpClient請求工具
* @author kaifeng
* @date 2017年2月27日 下午5:33:10
*
*/
@Service
public class HttpClientService
{
    @Autowired
    private CloseableHttpClient httpClient;
    @Autowired
    private RequestConfig requestConfig;

    /**
    * @Title: doGet
    * @Description: 執(zhí)行g(shù)et請求,200返回響應(yīng)內(nèi)容,其他狀態(tài)碼返回null
    * @Author kaifeng
    * @Date 2017年2月27日 下午5:24:09
    * @param url 請求地址
    * @return
    * @throws IOException
    * @throws
    */
    public String doGet(String url) throws IOException
    {
        //創(chuàng)建httpClient對象
        CloseableHttpResponse response = null;
        HttpGet httpGet = new HttpGet(url);
        //設(shè)置請求參數(shù)
        httpGet.setConfig(requestConfig);
        try
        {
            //執(zhí)行請求
            response = httpClient.execute(httpGet);
            //判斷返回狀態(tài)碼是否為200
            if (response.getStatusLine().getStatusCode() == 200)
            {               
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        }
        finally
        {
            if (response != null)
            {
                response.close();
            }
        }
        return null;
    }

    /**
    * @Title: doGet
    * @Description: 執(zhí)行帶有參數(shù)的get請求
    * @Author kaifeng
    * @Date 2017年2月27日 下午5:24:33
    * @param url 請求地址
    * @param paramMap 參數(shù)鍵值對
    * @return
    * @throws IOException
    * @throws URISyntaxException
    * @throws
    */
    public String doGet(String url, Map<String, String> paramMap)
            throws IOException, URISyntaxException
    {
        URIBuilder builder = new URIBuilder(url);
        for (String s : paramMap.keySet())
        {
            builder.addParameter(s, paramMap.get(s));
        }
        return doGet(builder.build().toString());
    }

    /**
    * @Title: doPost
    * @Description: 執(zhí)行post請求(有參數(shù))
    * @Author kaifeng
    * @Date 2017年2月27日 下午5:25:38
    * @param url 請求地址
    * @param paramMap 參數(shù)鍵值對
    * @return
    * @throws IOException
    * @throws
    */
    public HttpResult doPost(String url, Map<String, String> paramMap)
            throws IOException
    {
        HttpPost httpPost = new HttpPost(url);
        //設(shè)置請求參數(shù)
        httpPost.setConfig(requestConfig);
        if (paramMap != null)
        {
            List<NameValuePair> parameters = Lists.newArrayList();
            for (String s : paramMap.keySet())
            {
                parameters.add(new BasicNameValuePair(s, paramMap.get(s)));
            }
            //構(gòu)建一個form表單式的實體
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    parameters, Charset.forName("UTF-8"));
            //將請求實體放入到httpPost中
            httpPost.setEntity(formEntity);
        }
        //創(chuàng)建httpClient對象
        CloseableHttpResponse response = null;
        try
        {
            //執(zhí)行請求
            response = httpClient.execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity()));
        }
        finally
        {
            if (response != null)
            {
                response.close();
            }
        }
    }

    /**
    * @Title: doPost
    * @Description: 執(zhí)行post請求(無參數(shù))
    * @Author kaifeng
    * @Date 2017年2月27日 下午5:26:26
    * @param url 請求地址
    * @return
    * @throws IOException
    * @throws
    */
    public HttpResult doPost(String url) throws IOException
    {
        return doPost(url, null);
    }

    /**
    * @Title: doPostJson
    * @Description: POST請求(JSON格式參數(shù))
    * @Author kaifeng
    * @Date 2017年2月27日 下午5:27:04
    * @param url 請求地址
    * @param json 請求參數(shù)為JSON格式
    * @return
    * @throws ClientProtocolException
    * @throws IOException
    * @throws
    */
    public HttpResult doPostJson(String url, String json)
            throws ClientProtocolException, IOException
    {
        // 創(chuàng)建http POST請求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(this.requestConfig);

        if (json != null)
        {
            // 構(gòu)造一個請求實體
            StringEntity stringEntity = new StringEntity(json,
                    ContentType.APPLICATION_JSON);
            // 將請求實體設(shè)置到httpPost對象中
            httpPost.setEntity(stringEntity);
        }
        CloseableHttpResponse response = null;
        try
        {
            // 執(zhí)行請求
            response = this.httpClient.execute(httpPost);
            return new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        }
        finally
        {
            if (response != null)
            {
                response.close();
            }
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末赏胚,一起剝皮案震驚了整個濱河市访娶,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌觉阅,老刑警劉巖崖疤,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異留拾,居然都是意外死亡戳晌,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進(jìn)店門痴柔,熙熙樓的掌柜王于貴愁眉苦臉地迎上來沦偎,“玉大人,你說我怎么就攤上這事咳蔚『篮浚” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵谈火,是天一觀的道長侈询。 經(jīng)常有香客問我,道長糯耍,這世上最難降的妖魔是什么扔字? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮温技,結(jié)果婚禮上革为,老公的妹妹穿的比我還像新娘。我一直安慰自己舵鳞,他們只是感情好震檩,可當(dāng)我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著蜓堕,像睡著了一般抛虏。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上套才,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天迂猴,我揣著相機與錄音,去河邊找鬼背伴。 笑死沸毁,一個胖子當(dāng)著我的面吹牛儡率,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播以清,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼崎逃!你這毒婦竟也來了掷倔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤个绍,失蹤者是張志新(化名)和其女友劉穎勒葱,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體巴柿,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡凛虽,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了广恢。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片凯旋。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖钉迷,靈堂內(nèi)的尸體忽然破棺而出至非,到底是詐尸還是另有隱情,我是刑警寧澤糠聪,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布荒椭,位于F島的核電站,受9級特大地震影響舰蟆,放射性物質(zhì)發(fā)生泄漏趣惠。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一身害、第九天 我趴在偏房一處隱蔽的房頂上張望味悄。 院中可真熱鬧,春花似錦题造、人聲如沸傍菇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽丢习。三九已至,卻和暖如春淮悼,著一層夾襖步出監(jiān)牢的瞬間咐低,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工袜腥, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留见擦,地道東北人钉汗。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像鲤屡,于是被迫代替她去往敵國和親损痰。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容