最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

HttpClient詳細使用示例代碼

 更新時間:2022年07月20日 11:26:56   作者:怪 咖@  
這篇文章主要介紹了HttpClient詳細使用示例,包括導(dǎo)入依賴,使用工具類的詳細代碼,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1、導(dǎo)入依賴

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

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
</dependency>

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

 <dependency>
     <groupId>org.apache.httpcomponents</groupId>
     <artifactId>httpcore</artifactId>
     <version>4.4.13</version>
 </dependency>
 
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.7</version>
</dependency>

2、使用工具類

該工具類將get請求和post請求當(dāng)中幾種傳參方式都寫了,其中有g(shù)et地址欄傳參、get的params傳參、post的params傳參、post的json傳參。

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

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

    private static final int DEFULT_TIMEOUT = 30 * 1000;//默認超時時間20秒

    /**
     * 可以訪問  http://localhost:9005/yzhwsj/addPersonal/1/2 這樣的接口
     * @param url
     * @param headers
     * @param urlParam
     * @param timeout
     * @return
     */
    private static String doUrlGet(String url, Map<String, String> headers, List<String> urlParam, Integer timeout) {
        //創(chuàng)建httpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            //創(chuàng)建uri
            if (urlParam != null){
                for (String param : urlParam) {
                    url = url + "/" + param;
                }
            }
            //創(chuàng)建hTTP get請求
            HttpGet httpGet = new HttpGet(url);
            //設(shè)置超時時間
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpGet.setConfig(requestConfig);
            //設(shè)置頭信息
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpGet.setHeader(key, headers.get(key));
                }
            }
            //執(zhí)行請求
            response = httpClient.execute(httpGet);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (IOException e) {
            logger.error("http調(diào)用異常" + e.toString(), e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("response關(guān)閉異常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("httpClient關(guān)閉異常" + e.toString(), e);
            }
        }
        return resultString;
    }

    /**
     * @param url
     * @param headers
     * @param params
     * @param timeout
     * @return
     */
    private static String doGet(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {
        //創(chuàng)建httpClient對象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            // 1.創(chuàng)建uri
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
                //uri添加參數(shù)
                for (String key : params.keySet()) {
                    builder.addParameter(key, String.valueOf(params.get(key)));
                }
            }
            URI uri = builder.build();
            // 2.創(chuàng)建hTTP get請求
            HttpGet httpGet = new HttpGet(uri);
            // 3.設(shè)置超時時間
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpGet.setConfig(requestConfig);
            // 4.設(shè)置頭信息
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpGet.setHeader(key, headers.get(key));
                }
            }
            // 5.執(zhí)行請求
            response = httpClient.execute(httpGet);
            if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (URISyntaxException e) {
            logger.error("http調(diào)用異常" + e.toString(), e);
        } catch (IOException e) {
            logger.error("http調(diào)用異常" + e.toString(), e);

        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("response關(guān)閉異常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("httpClient關(guān)閉異常" + e.toString(), e);
            }
        }
        return resultString;
    }

    /**
     * 調(diào)用http post請求(json數(shù)據(jù))
     *
     * @param url
     * @param headers
     * @param json
     * @return
     */
    public static String doJsonPost(String url, Map<String, String> headers, JSONObject json, Integer timeout) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 1.創(chuàng)建http post請求
            HttpPost httpPost = new HttpPost(url);
            // 2.設(shè)置超時時間
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);
            // 3.設(shè)置參數(shù)信息
            StringEntity s = new StringEntity(json.toString(), Consts.UTF_8);
            // 發(fā)送json數(shù)據(jù)需要設(shè)置的contentType
            s.setContentType("application/json");
            httpPost.setEntity(s);
            // 4.設(shè)置頭信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }
            // 5.執(zhí)行http請求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("調(diào)用http異常" + e.toString(), e);
        } catch (ClientProtocolException e) {
            logger.error("調(diào)用http異常" + e.toString(), e);
        } catch (IOException e) {
            logger.error("調(diào)用http異常" + e.toString(), e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉response異常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉httpClient異常" + e.toString(), e);
            }
        }
        return resultString;
    }

    /**
     * 調(diào)用http post請求 基礎(chǔ)方法
     *
     * @param url     請求的url
     * @param headers 請求頭
     * @param params  參數(shù)
     * @param timeout 超時時間
     * @return
     */
    public static String doPost(String url, Map<String, String> headers, Map<String, Object> params, Integer timeout) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 1.創(chuàng)建http post請求
            HttpPost httpPost = new HttpPost(url);
            // 2.設(shè)置超時時間
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);
            // 3.設(shè)置參數(shù)信息
            if (params != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : params.keySet()) {
                    paramList.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
                }
                // 模擬表單
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, Consts.UTF_8);
                httpPost.setEntity(entity);
            }
            // 4.設(shè)置頭信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }
            // 5.執(zhí)行http請求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("調(diào)用http異常" + e.toString(), e);
        } catch (ClientProtocolException e) {
            logger.error("調(diào)用http異常" + e.toString(), e);
        } catch (IOException e) {
            logger.error("調(diào)用http異常" + e.toString(), e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉response異常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉httpClient異常" + e.toString(), e);
            }
        }
        return resultString;
    }
    
	/**
     * 通過httpClient上傳文件
     *
     * @param url      請求的URL
     * @param headers  請求頭參數(shù)
     * @param path     文件路徑
     * @param fileName 文件名稱
     * @param timeout  超時時間
     * @return
     */
    public static String UploadFileByHttpClient(String url, Map<String, String> headers, String path, String fileName, Integer timeout) {
        String resultString = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream content = null;
        BufferedReader in = null;
        try {
            // 1.創(chuàng)建http post請求
            HttpPost httpPost = new HttpPost(url);

            // 2.設(shè)置超時時間
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);

            // 3.設(shè)置參數(shù)信息
            // HttpMultipartMode.RFC6532參數(shù)的設(shè)定是為避免文件名為中文時亂碼
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            // 上傳文件的路徑
            File file = new File(path + File.separator + fileName);
            builder.setCharset(Charset.forName("UTF-8"));
            builder.addBinaryBody("file", file, ContentType.MULTIPART_FORM_DATA, fileName);
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            // 4.設(shè)置頭信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }

            // 5.執(zhí)行http請求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            logger.error("上傳文件失敗:", e);
        } finally {
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉httpClient異常" + e.toString(), e);
            }
            try {
                if (null != content) {
                    content.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉content異常" + e.toString(), e);
            }
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉in異常" + e.toString(), e);
            }
        }

        return resultString;
    }
 }

	/**
     * 通過httpClient批量上傳文件
     *
     * @param url     請求的URL
     * @param headers 請求頭參數(shù)
     * @param params  參數(shù)
     * @param paths   文件路徑(key文件名稱,value路徑)
     * @param timeout 超時時間
     * @return
     */
    public static String UploadFilesByHttpClient(String url, Map<String, String> headers, Map<String, String> params, Map<String, String> paths, Integer timeout) {
        String resultString = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        InputStream content = null;
        BufferedReader in = null;
        try {
            // 1.創(chuàng)建http post請求
            HttpPost httpPost = new HttpPost(url);

            // 2.設(shè)置超時時間
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);

            // 3.設(shè)置文件信息
            // HttpMultipartMode.RFC6532參數(shù)的設(shè)定是為避免文件名為中文時亂碼
            MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
            builder.setCharset(Charset.forName("UTF-8"));
            // 上傳文件的路徑
            for (Map.Entry<String, String> m : paths.entrySet()) {
                File file = new File(m.getValue() + File.separator + m.getKey());
                builder.addBinaryBody("files", file, ContentType.MULTIPART_FORM_DATA, m.getKey());
            }

            // 4.設(shè)置參數(shù)信息
            ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
            for (Map.Entry<String, String> param : params.entrySet()) {
                builder.addTextBody(param.getKey(), param.getValue(), contentType);
            }
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);

            // 5.設(shè)置頭信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }

            // 6.執(zhí)行http請求
            response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                resultString = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
            }
        } catch (Exception e) {
            logger.error("上傳文件失?。?, e);
        } finally {
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉httpClient異常" + e.toString(), e);
            }
            try {
                if (null != content) {
                    content.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉content異常" + e.toString(), e);
            }
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("關(guān)閉in異常" + e.toString(), e);
            }
        }

        return resultString;
    }

3、擴展

上面的工具類,方法都攜帶了token和超時時間,假如接口用不到可以做接口拓展。例如:

/**
 * 調(diào)用http get請求
 *
 * @param url
 * @param params
 * @return
 */
public static String doGet(String url, Map<String, Object> params) {
    return doGet(url, null, params, null);
}

如果涉及到put請求和delete請求,跟上面都差不多,只不過創(chuàng)建請求的時候改為:

HttpDelete httpDelete = new HttpDelete();
HttpPut httpPut = new HttpPut();

到此這篇關(guān)于HttpClient詳細使用示例的文章就介紹到這了,更多相關(guān)HttpClient使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringCloud持久層框架MyBatis Plus的使用與原理解析

    SpringCloud持久層框架MyBatis Plus的使用與原理解析

    MyBatisPlus為MyBatis的增強版,專注于簡化數(shù)據(jù)庫操作,提供自動化CRUD、內(nèi)置分頁和樂觀鎖等功能,極大提升開發(fā)效率,在SpringCloud微服務(wù)架構(gòu)中,MyBatisPlus通過插件機制和自動生成代碼功能,有效支持企業(yè)級應(yīng)用和分布式系統(tǒng)的開發(fā)
    2024-10-10
  • 解決springboot報錯Failed?to?parse?multipart?servlet?request;?nested?exception?is?java.io.IOException問題

    解決springboot報錯Failed?to?parse?multipart?servlet?request

    在使用SpringBoot開發(fā)時,通過Postman發(fā)送POST請求,可能會遇到因臨時目錄不存在而導(dǎo)致的MultipartException異常,這通常是因為OS系統(tǒng)(如CentOS)定期刪除/tmp目錄下的臨時文件,解決方案包括重啟項目
    2024-10-10
  • SpringBoot中使用AOP實現(xiàn)日志記錄功能

    SpringBoot中使用AOP實現(xiàn)日志記錄功能

    AOP的全稱是Aspect-Oriented Programming,即面向切面編程(也稱面向方面編程),它是面向?qū)ο缶幊蹋∣OP)的一種補充,目前已成為一種比較成熟的編程方式,本文給大家介紹了SpringBoot中使用AOP實現(xiàn)日志記錄功能,需要的朋友可以參考下
    2024-05-05
  • JNI語言基本知識

    JNI語言基本知識

    JNI是Java Native Interface的縮寫,它提供了若干的API實現(xiàn)了Java和其他語言的通信(主要是C&C++)。接下來通過本文給大家分享jni 基礎(chǔ)知識,感興趣的朋友一起看看吧
    2017-10-10
  • Java簡明解讀代碼塊的應(yīng)用

    Java簡明解讀代碼塊的應(yīng)用

    所謂代碼塊是指用"{}"括起來的一段代碼,根據(jù)其位置和聲明的不同,可以分為普通代碼塊、構(gòu)造塊、靜態(tài)塊、和同步代碼塊。如果在代碼塊前加上 synchronized關(guān)鍵字,則此代碼塊就成為同步代碼塊
    2022-07-07
  • Spring中事務(wù)管理的四種方法(銀行轉(zhuǎn)賬為例)

    Spring中事務(wù)管理的四種方法(銀行轉(zhuǎn)賬為例)

    這篇文章主要給大家介紹了關(guān)于Spring中事務(wù)管理的四種方法,文中是以銀行轉(zhuǎn)賬為例,通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2018-05-05
  • springboot訪問template下的html頁面的實現(xiàn)配置

    springboot訪問template下的html頁面的實現(xiàn)配置

    這篇文章主要介紹了springboot訪問template下的html頁面的實現(xiàn)配置,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • springboot整合騰訊云短信開箱即用的示例代碼

    springboot整合騰訊云短信開箱即用的示例代碼

    這篇文章主要介紹了springboot整合騰訊云短信開箱即用,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-03-03
  • 解決java調(diào)用dll報Unable to load library錯誤的問題

    解決java調(diào)用dll報Unable to load library錯誤的問題

    這篇文章主要介紹了解決java調(diào)用dll報Unable to load library錯誤的問題。具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • Springboot中的三個基本架構(gòu)

    Springboot中的三個基本架構(gòu)

    這篇文章主要介紹了Springboot中的三個基本架構(gòu),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-07-07

最新評論

紫阳县| 和林格尔县| 无极县| 开鲁县| 中牟县| 衡阳县| 南澳县| 神农架林区| 乌兰察布市| 兴和县| 中牟县| 乌鲁木齐市| 郓城县| 无极县| 长治县| 通道| 九江市| 龙州县| 台湾省| 沽源县| 洛隆县| 泸定县| 伊吾县| 荥经县| 陆川县| 新和县| 兴山县| 建德市| 称多县| 竹北市| 南丹县| 衢州市| 乌拉特后旗| 崇文区| 东乌| 辽宁省| 三穗县| 衡南县| 中宁县| 玉山县| 渭源县|