目錄
1、導入依賴
2、使用工具類別
3、擴充
首頁 Java java教程 如何使用Java HttpClient發送HTTP請求

如何使用Java HttpClient發送HTTP請求

Apr 20, 2023 pm 11:49 PM
java httpclient

1、導入依賴

<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請求當中幾種傳參方式都寫了,其中有get網址列傳參、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) {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            //创建uri
            if (urlParam != null){
                for (String param : urlParam) {
                    url = url + "/" + param;
                }
            }
            //创建hTTP get请求
            HttpGet httpGet = new HttpGet(url);
            //设置超时时间
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpGet.setConfig(requestConfig);
            //设置头信息
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpGet.setHeader(key, headers.get(key));
                }
            }
            //执行请求
            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调用异常" + e.toString(), e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("response关闭异常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("httpClient关闭异常" + 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) {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultString = null;
        CloseableHttpResponse response = null;
        try {
            // 1.创建uri
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
                //uri添加参数
                for (String key : params.keySet()) {
                    builder.addParameter(key, String.valueOf(params.get(key)));
                }
            }
            URI uri = builder.build();
            // 2.创建hTTP get请求
            HttpGet httpGet = new HttpGet(uri);
            // 3.设置超时时间
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpGet.setConfig(requestConfig);
            // 4.设置头信息
            if (null != headers) {
                for (String key : headers.keySet()) {
                    httpGet.setHeader(key, headers.get(key));
                }
            }
            // 5.执行请求
            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调用异常" + e.toString(), e);
        } catch (IOException e) {
            logger.error("http调用异常" + e.toString(), e);

        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("response关闭异常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("httpClient关闭异常" + e.toString(), e);
            }
        }
        return resultString;
    }

    /**
     * 调用http post请求(json数据)
     *
     * @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.创建http post请求
            HttpPost httpPost = new HttpPost(url);
            // 2.设置超时时间
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);
            // 3.设置参数信息
            StringEntity s = new StringEntity(json.toString(), Consts.UTF_8);
            // 发送json数据需要设置的contentType
            s.setContentType("application/json");
            httpPost.setEntity(s);
            // 4.设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }
            // 5.执行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("调用http异常" + e.toString(), e);
        } catch (ClientProtocolException e) {
            logger.error("调用http异常" + e.toString(), e);
        } catch (IOException e) {
            logger.error("调用http异常" + e.toString(), e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("关闭response异常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("关闭httpClient异常" + e.toString(), e);
            }
        }
        return resultString;
    }

    /**
     * 调用http post请求 基础方法
     *
     * @param url     请求的url
     * @param headers 请求头
     * @param params  参数
     * @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.创建http post请求
            HttpPost httpPost = new HttpPost(url);
            // 2.设置超时时间
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);
            // 3.设置参数信息
            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.设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }
            // 5.执行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("调用http异常" + e.toString(), e);
        } catch (ClientProtocolException e) {
            logger.error("调用http异常" + e.toString(), e);
        } catch (IOException e) {
            logger.error("调用http异常" + e.toString(), e);
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                logger.error("关闭response异常" + e.toString(), e);
            }
            try {
                if (null != httpClient) {
                    httpClient.close();
                }
            } catch (IOException e) {
                logger.error("关闭httpClient异常" + e.toString(), e);
            }
        }
        return resultString;
    }
    
	/**
     * 通过httpClient上传文件
     *
     * @param url      请求的URL
     * @param headers  请求头参数
     * @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.创建http post请求
            HttpPost httpPost = new HttpPost(url);

            // 2.设置超时时间
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);

            // 3.设置参数信息
            // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            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.设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }

            // 5.执行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("关闭httpClient异常" + e.toString(), e);
            }
            try {
                if (null != content) {
                    content.close();
                }
            } catch (IOException e) {
                logger.error("关闭content异常" + e.toString(), e);
            }
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("关闭in异常" + e.toString(), e);
            }
        }

        return resultString;
    }
 }

	/**
     * 通过httpClient批量上传文件
     *
     * @param url     请求的URL
     * @param headers 请求头参数
     * @param params  参数
     * @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.创建http post请求
            HttpPost httpPost = new HttpPost(url);

            // 2.设置超时时间
            int timeoutTmp = DEFULT_TIMEOUT;
            if (timeout != null) {
                timeoutTmp = timeout;
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(timeoutTmp)
                    .setConnectionRequestTimeout(timeoutTmp).setSocketTimeout(timeoutTmp).build();
            httpPost.setConfig(requestConfig);

            // 3.设置文件信息
            // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            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.设置参数信息
            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.设置头信息
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpPost.setHeader(key, headers.get(key));
                }
            }

            // 6.执行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("关闭httpClient异常" + e.toString(), e);
            }
            try {
                if (null != content) {
                    content.close();
                }
            } catch (IOException e) {
                logger.error("关闭content异常" + e.toString(), e);
            }
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("关闭in异常" + e.toString(), e);
            }
        }

        return resultString;
    }
登入後複製

3、擴充

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

/**
 * 调用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請求,跟上面都差不多,只不過創建請求的時候改為:

HttpDelete httpDelete = new HttpDelete();

HttpPut httpPut = new HttpPut();
登入後複製

以上是如何使用Java HttpClient發送HTTP請求的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.聊天命令以及如何使用它們
1 個月前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Java 中的完美數 Java 中的完美數 Aug 30, 2024 pm 04:28 PM

Java 完美數指南。這裡我們討論定義,如何在 Java 中檢查完美數?

Java 中的隨機數產生器 Java 中的隨機數產生器 Aug 30, 2024 pm 04:27 PM

Java 隨機數產生器指南。在這裡,我們透過範例討論 Java 中的函數,並透過範例討論兩個不同的生成器。

Java中的Weka Java中的Weka Aug 30, 2024 pm 04:28 PM

Java 版 Weka 指南。這裡我們透過範例討論簡介、如何使用 weka java、平台類型和優點。

Java 中的史密斯數 Java 中的史密斯數 Aug 30, 2024 pm 04:28 PM

Java 史密斯數指南。這裡我們討論定義,如何在Java中檢查史密斯號?帶有程式碼實現的範例。

Java Spring 面試題 Java Spring 面試題 Aug 30, 2024 pm 04:29 PM

在本文中,我們保留了最常被問到的 Java Spring 面試問題及其詳細答案。這樣你就可以順利通過面試。

突破或從Java 8流返回? 突破或從Java 8流返回? Feb 07, 2025 pm 12:09 PM

Java 8引入了Stream API,提供了一種強大且表達力豐富的處理數據集合的方式。然而,使用Stream時,一個常見問題是:如何從forEach操作中中斷或返回? 傳統循環允許提前中斷或返回,但Stream的forEach方法並不直接支持這種方式。本文將解釋原因,並探討在Stream處理系統中實現提前終止的替代方法。 延伸閱讀: Java Stream API改進 理解Stream forEach forEach方法是一個終端操作,它對Stream中的每個元素執行一個操作。它的設計意圖是處

Java 中的時間戳至今 Java 中的時間戳至今 Aug 30, 2024 pm 04:28 PM

Java 中的時間戳記到日期指南。這裡我們也結合範例討論了介紹以及如何在java中將時間戳記轉換為日期。

Java程序查找膠囊的體積 Java程序查找膠囊的體積 Feb 07, 2025 am 11:37 AM

膠囊是一種三維幾何圖形,由一個圓柱體和兩端各一個半球體組成。膠囊的體積可以通過將圓柱體的體積和兩端半球體的體積相加來計算。本教程將討論如何使用不同的方法在Java中計算給定膠囊的體積。 膠囊體積公式 膠囊體積的公式如下: 膠囊體積 = 圓柱體體積 兩個半球體體積 其中, r: 半球體的半徑。 h: 圓柱體的高度(不包括半球體)。 例子 1 輸入 半徑 = 5 單位 高度 = 10 單位 輸出 體積 = 1570.8 立方單位 解釋 使用公式計算體積: 體積 = π × r2 × h (4

See all articles