HttpClient中post get請求http、https示例

使用HttpClient發(fā)送請求翘盖、接收響應(yīng)很簡單桂塞,一般需要如下幾步即可:

  • 創(chuàng)建CloseableHttpClient對象。
  • 創(chuàng)建請求方法的實(shí)例馍驯,并指定請求URL阁危。如果需要發(fā)送GET請求,創(chuàng)建HttpGet對象汰瘫;如果需要發(fā)送POST請求狂打,創(chuàng)建HttpPost對象。
  • 如果需要發(fā)送請求參數(shù)混弥,可可調(diào)用setEntity(HttpEntity entity)方法來設(shè)置請求參數(shù)趴乡。setParams方法已過時(4.4.1版本)。
  • 調(diào)用HttpGet蝗拿、HttpPost對象的setHeader(String name, String value)方法設(shè)置header信息晾捏,或者調(diào)用setHeaders(Header[] headers)設(shè)置一組header信息。
  • 調(diào)用CloseableHttpClient對象的execute(HttpUriRequest request)發(fā)送請求哀托,該方法返回一個CloseableHttpResponse惦辛。
  • 調(diào)用HttpResponse的getEntity()方法可獲取HttpEntity對象,該對象包裝了服務(wù)器的響應(yīng)內(nèi)容仓手。程序可通過該對象獲取服務(wù)器的響應(yīng)內(nèi)容胖齐;調(diào)用CloseableHttpResponse的getAllHeaders()玻淑、getHeaders(String name)等方法可獲取服務(wù)器的響應(yīng)頭。
  • 釋放連接呀伙。無論執(zhí)行方法是否成功补履,都必須釋放連接

首先使用maven添加依賴:

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

具體代碼如下:

/**
 * @Author: grootdu
 * @Description:
 * @Date: Created in 11:56 2018/11/17
 * @Modified By:
 */
public class HttpClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doGet(String url, Map<String, String> params, Map<String, String> headers, RequestConfig config) throws Exception{
        String res = "";
        // 創(chuàng)建Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        // 創(chuàng)建uri
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (String key : params.keySet()) {
                builder.addParameter(key, params.get(key));
            }
        }
        URI uri = builder.build();
        // 創(chuàng)建http GET請求
        HttpGet httpGet = new HttpGet(uri);
//        HttpGet httpGet = new HttpGet(url);//如果url后面帶了全部參數(shù)的話 也可以直接用這種方式直接創(chuàng)建get請求
        if (headers != null) {
            for (String key : headers.keySet()) {
                httpGet.addHeader(key, headers.get(key));
            }
        }
        try {
            if(config!=null){
                // 構(gòu)建請求配置信息
//                RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 創(chuàng)建連接的最長時間
//                    .setConnectionRequestTimeout(500) // 從連接池中獲取到連接的最長時間
//                    .setSocketTimeout(10 * 1000) // 數(shù)據(jù)傳輸?shù)淖铋L時間
//                    .setStaleConnectionCheckEnabled(true) // 提交請求前測試連接是否可用
//                    .build();
                httpGet.setConfig(config);
            }
            // 執(zhí)行請求操作,并拿到結(jié)果(同步阻塞)
            response = httpClient.execute(httpGet);
            //獲取結(jié)果實(shí)體
            HttpEntity entity = response.getEntity();
            // 判斷返回狀態(tài)是否為200
            if (response.getStatusLine().getStatusCode() == 200 && entity != null) {
                //按指定編碼(這里為UTF8編碼)轉(zhuǎn)換結(jié)果實(shí)體為String類型
                res = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpGet.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }

    public static String doPost(String url, RequestConfig config)  throws Exception {
        return doPost(url, null,config);
    }

    public static String doPost(String url, Map<String, String> params, RequestConfig config, Map<String, String> headParams)  throws Exception {
        //對于params中key value剿另,如果是其他類型干像,比如數(shù)組的話,用下面的doPostJson方法更適合驰弄,即直接將入?yún)⑵闯蒵son字符串,JSONObject.toJSONString(map)
        String res = "";
        // 創(chuàng)建Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 創(chuàng)建Http Post請求對象
        HttpPost httpPost = new HttpPost(url);
        if(headParams != null){
            for(String key : headParams.keySet()){
                httpPost.addHeader(key, headParams.get(key));
            }
        }
        try {
            if(config!=null){
                httpPost.setConfig(config);
            }
            // 創(chuàng)建參數(shù)列表
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<NameValuePair>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, params.get(key)));
                }
                // 創(chuàng)建請求內(nèi)容
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                // 設(shè)置參數(shù)到請求對象中
                httpPost.setEntity(entity);
            }
            // 執(zhí)行http請求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            res = EntityUtils.toString(response.getEntity(), "utf-8");
        }  catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }

    public static String doPostJson(String url, String json, RequestConfig config)  throws Exception {
        String res = "";
        // 創(chuàng)建Httpclient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 創(chuàng)建Http Post請求
        HttpPost httpPost = new HttpPost(url);
        try {
            if (config != null) {
                httpPost.setConfig(config);
            }
            // 設(shè)置參數(shù)到請求對象中
            httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
            // 執(zhí)行http請求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            // 獲取結(jié)果實(shí)體
            HttpEntity entity = response.getEntity();
            if(entity != null){
                res = EntityUtils.toString(entity, "utf-8");   
            }
        }   catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }
    
    public static byte[] doPost(String url, byte[] data) throws Exception {
        byte[] res = null;

        HttpPost httpPost = new HttpPost(url);
        //CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build();    // disable retry

        try {
            // init post
            /*if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8"));
            }*/

            // timeout
            RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(10000)
                .setSocketTimeout(10000)
                .setConnectTimeout(10000)
                .build();

            httpPost.setConfig(requestConfig);

            // data
            if (data != null) {
                httpPost.setEntity(new ByteArrayEntity(data, ContentType.DEFAULT_BINARY));
            }
            // do post
            HttpResponse response = httpClient.execute(httpPost);
            // 獲取結(jié)果實(shí)體
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                res = EntityUtils.toByteArray(entity);
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpPost.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }

    /**
     * read bytes from http request
     * @param request
     * @return
     * @throws IOException
     */
    public static final byte[] readBytes(HttpServletRequest request) throws IOException {
        request.setCharacterEncoding("UTF-8");
        int contentLen = request.getContentLength();
        InputStream is = request.getInputStream();
        if (contentLen > 0) {
            int readLen = 0;
            int readLengthThisTime = 0;
            byte[] message = new byte[contentLen];
            try {
                while (readLen != contentLen) {
                    readLengthThisTime = is.read(message, readLen, contentLen - readLen);
                    if (readLengthThisTime == -1) {
                        break;
                    }
                    readLen += readLengthThisTime;
                }
                return message;
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw e;
            }
        }
        return new byte[] {};
    }
}

對于HTTPS的訪問速客,采取繞過證書的策略:

/**
 * @Author: grootdu
 * @Description:
 * @Date: Created in 16:12 2018/11/14
 * @Modified By:
 */
public class HttpsClientUtil {

    private static Logger logger = LoggerFactory.getLogger(HttpsClientUtil.class);
    /**
     * 繞過驗(yàn)證
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 實(shí)現(xiàn)一個X509TrustManager接口戚篙,用于繞過驗(yàn)證,不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[] { trustManager }, null);
        return sc;
    }

    /**
     * 模擬請求
     *
     * @param url        
     * @param param    
     * @param
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     * @throws ClientProtocolException
     */
    public static String doGet(String url, Map<String,String> param, RequestConfig config) throws Exception {
        String res = "";
        //采用繞過驗(yàn)證的方式處理https請求
        SSLContext sslcontext = createIgnoreVerifySSL();
        // 設(shè)置協(xié)議http和https對應(yīng)的處理socket鏈接工廠的對象
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext))
            .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        //創(chuàng)建自定義的httpclient對象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager).build();
        // 創(chuàng)建uri
        URIBuilder builder = new URIBuilder(url);
        if (param != null) {
            for (String key : param.keySet()) {
                builder.addParameter(key, param.get(key));
            }
        }
        URI uri = builder.build();
        // 創(chuàng)建http GET請求
        HttpGet httpGet = new HttpGet(uri);
        try {
            if(config!=null){
                httpGet.setConfig(config);
            }
            // 執(zhí)行請求
            CloseableHttpResponse response = httpClient.execute(httpGet);
            // 判斷返回狀態(tài)是否為200
            if (response.getStatusLine().getStatusCode() == 200) {
                res = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw e;
        } finally {
            httpGet.releaseConnection();
            try {
                httpClient.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return res;
    }
}

參考博客:
https://www.cnblogs.com/Mr-Rocker/p/6229652.html
https://www.cnblogs.com/moy25/p/8658762.html
https://www.656463.com/article/httpclientqingqiucanshushezhi_8

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末溺职,一起剝皮案震驚了整個濱河市岔擂,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌浪耘,老刑警劉巖乱灵,帶你破解...
    沈念sama閱讀 222,681評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異七冲,居然都是意外死亡痛倚,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,205評論 3 399
  • 文/潘曉璐 我一進(jìn)店門澜躺,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蝉稳,“玉大人,你說我怎么就攤上這事掘鄙≡牌荩” “怎么了?”我有些...
    開封第一講書人閱讀 169,421評論 0 362
  • 文/不壞的土叔 我叫張陵操漠,是天一觀的道長收津。 經(jīng)常有香客問我,道長浊伙,這世上最難降的妖魔是什么撞秋? 我笑而不...
    開封第一講書人閱讀 60,114評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮嚣鄙,結(jié)果婚禮上部服,老公的妹妹穿的比我還像新娘。我一直安慰自己拗慨,他們只是感情好廓八,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,116評論 6 398
  • 文/花漫 我一把揭開白布奉芦。 她就那樣靜靜地躺著,像睡著了一般剧蹂。 火紅的嫁衣襯著肌膚如雪声功。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,713評論 1 312
  • 那天宠叼,我揣著相機(jī)與錄音先巴,去河邊找鬼。 笑死冒冬,一個胖子當(dāng)著我的面吹牛伸蚯,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播简烤,決...
    沈念sama閱讀 41,170評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼剂邮,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了横侦?” 一聲冷哼從身側(cè)響起挥萌,我...
    開封第一講書人閱讀 40,116評論 0 277
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎枉侧,沒想到半個月后引瀑,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,651評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡榨馁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,714評論 3 342
  • 正文 我和宋清朗相戀三年憨栽,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片翼虫。...
    茶點(diǎn)故事閱讀 40,865評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡徒像,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蛙讥,到底是詐尸還是另有隱情锯蛀,我是刑警寧澤,帶...
    沈念sama閱讀 36,527評論 5 351
  • 正文 年R本政府宣布次慢,位于F島的核電站旁涤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏迫像。R本人自食惡果不足惜劈愚,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,211評論 3 336
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望闻妓。 院中可真熱鬧菌羽,春花似錦、人聲如沸由缆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,699評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至是晨,卻和暖如春肚菠,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背罩缴。 一陣腳步聲響...
    開封第一講書人閱讀 33,814評論 1 274
  • 我被黑心中介騙來泰國打工蚊逢, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人箫章。 一個月前我還...
    沈念sama閱讀 49,299評論 3 379
  • 正文 我出身青樓烙荷,卻偏偏與公主長得像,于是被迫代替她去往敵國和親檬寂。 傳聞我的和親對象是個殘疾皇子终抽,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,870評論 2 361

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

  • 前言 超文本傳輸協(xié)議(HTTP)也許是當(dāng)今互聯(lián)網(wǎng)上使用的最重要的協(xié)議了。Web服務(wù)焰薄,有網(wǎng)絡(luò)功能的設(shè)備和網(wǎng)絡(luò)計(jì)算的發(fā)...
    狂奔的蝸牛_wxc閱讀 5,518評論 0 12
  • 簡介 HttpClient是Apache Jakarta Common下的子項(xiàng)目,用來提供高效的扒袖、最新的塞茅、功能豐富...
    梁朋舉閱讀 42,855評論 0 28
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)季率,斷路器野瘦,智...
    卡卡羅2017閱讀 134,716評論 18 139
  • apache下的httpclient工具可大大簡化開發(fā)過程中的點(diǎn)對點(diǎn)通信,本人將以微信多媒體接口為例飒泻,展示http...
    劃破的天空閱讀 5,301評論 0 32
  • 今天思考的主題“看書究竟該看些什么書” 不過是以前還是現(xiàn)在亦或是將來鞭光,愛讀書者讀書是永遠(yuǎn)不會過時的一件事,人們可以...
    丿子木丨閱讀 598評論 0 1