HttpClient使用方法總結(jié)及工具類封裝
2025-04-01 09:39 申城異鄉(xiāng)人 閱讀(1549) 評(píng)論(0) 收藏 舉報(bào)1. 引入httpclient依賴
首先,需要確認(rèn)項(xiàng)目中是否已引入過httpclient依賴,如果沒有引入過,需要在pom.xml中添加以下代碼引入httpclient依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2. 發(fā)送GET請(qǐng)求
2.1 發(fā)送GET請(qǐng)求(無參數(shù))
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doGet() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
2.2 發(fā)送GET請(qǐng)求(帶參數(shù))
第一種方法是直接在url上拼接上參數(shù),如下所示:
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");
第二種方法是使用URIBuilder添加參數(shù),如下所示:
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doGet() throws IOException, URISyntaxException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
URIBuilder uriBuilder = new URIBuilder("https://www.example.com/getDataList");
uriBuilder.addParameter("pageIndex", "1");
uriBuilder.addParameter("pageSize", "20");
HttpGet httpGet = new HttpGet(uriBuilder.build());
try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
3. 發(fā)送POST請(qǐng)求
3.1 發(fā)送POST請(qǐng)求(無參數(shù))
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
3.2 發(fā)送POST請(qǐng)求(帶參數(shù)、form表單方式)
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "新名字"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
httpPost.setEntity(formEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
3.3 發(fā)送POST請(qǐng)求(帶參數(shù)、json方式)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPost() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://www.example.com/updateData");
String jsonBody = "{\"id\":\"1\",\"name\":新名字}";
StringEntity stringEntity = new StringEntity(jsonBody);
stringEntity.setContentType("application/json;charset=utf-8");
httpPost.setEntity(stringEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
4. 發(fā)送PUT請(qǐng)求
4.1 發(fā)送PUT請(qǐng)求(無參數(shù))
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
4.2 發(fā)送PUT請(qǐng)求(帶參數(shù)、form表單方式)
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
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.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("id", "1"));
params.add(new BasicNameValuePair("name", "新名字"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, StandardCharsets.UTF_8);
httpPut.setEntity(formEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
4.3 發(fā)送PUT請(qǐng)求(帶參數(shù)、json方式)
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doPut() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPut httpPut = new HttpPut("https://www.example.com/updateData");
String jsonBody = "{\"id\":\"1\",\"name\":新名字}";
StringEntity stringEntity = new StringEntity(jsonBody);
stringEntity.setContentType("application/json;charset=utf-8");
httpPut.setEntity(stringEntity);
try (CloseableHttpResponse httpResponse = httpClient.execute(httpPut)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
5. 發(fā)送DELETE請(qǐng)求
5.1 發(fā)送DELETE請(qǐng)求(無參數(shù))
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class HttpClientUtils {
public static String doDelete() throws IOException {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpDelete httpDelete = new HttpDelete("https://www.example.com/updateData");
try (CloseableHttpResponse httpResponse = httpClient.execute(httpDelete)) {
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);
}
return null;
}
}
}
}
6. 添加請(qǐng)求頭
一般情況下,請(qǐng)求第三方接口都需要簽名、時(shí)間戳等請(qǐng)求頭,以POST請(qǐng)求為例,添加請(qǐng)求頭的代碼如下所示:
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("signature", "3045022100875efcef9eb54626bb0168a6baa7c61265d0001d49243f");
httpPost.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));
GET請(qǐng)求、PUT請(qǐng)求、DELETE請(qǐng)求添加請(qǐng)求頭的方法同上。
7. 超時(shí)時(shí)間設(shè)置
如果需要自定義HTTP請(qǐng)求的連接超時(shí)時(shí)間和數(shù)據(jù)傳輸超時(shí)時(shí)間,代碼如下所示(以POST請(qǐng)求為例):
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(requestConfig);
GET請(qǐng)求、PUT請(qǐng)求、DELETE請(qǐng)求設(shè)置超時(shí)時(shí)間的方法同上。
8.工具類封裝
完整的工具類代碼如下所示:
import org.apache.http.HttpEntity;
import org.apache.http.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.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.ContentType;
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.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class HttpClientUtils {
/**
* 連接建立超時(shí)時(shí)間(單位:毫秒)
*/
private static final int CONNECT_TIMEOUT = 5000;
/**
* 數(shù)據(jù)傳輸超時(shí)時(shí)間(單位:毫秒)
*/
private static final int SOCKET_TIMEOUT = 10000;
/**
* 執(zhí)行GET請(qǐng)求
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doGet(String url, Map<String, String> headers) throws IOException {
HttpGet httpGet = new HttpGet(url);
// 設(shè)置請(qǐng)求頭
setHeaders(httpGet, headers);
return executeRequest(httpGet);
}
/**
* 執(zhí)行GET請(qǐng)求
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @param params 請(qǐng)求參數(shù)
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(url);
// 設(shè)置請(qǐng)求參數(shù)
if (params != null && !params.isEmpty()) {
for (Map.Entry<String, String> entry : params.entrySet()) {
uriBuilder.setParameter(entry.getKey(), entry.getValue());
}
}
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 設(shè)置請(qǐng)求頭
setHeaders(httpGet, headers);
return executeRequest(httpGet);
}
/**
* 執(zhí)行POST請(qǐng)求(表單方式)
*
* @param url 請(qǐng)求地址
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doPost(String url) throws IOException {
return doPost(url, null, null);
}
/**
* 執(zhí)行POST請(qǐng)求(表單方式)
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doPost(String url, Map<String, String> headers) throws IOException {
return doPost(url, headers, null);
}
/**
* 執(zhí)行POST請(qǐng)求(表單方式)
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @param params 請(qǐng)求參數(shù)
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
// 設(shè)置請(qǐng)求頭
setHeaders(httpPost, headers);
// 構(gòu)建表單參數(shù)
if (params != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
httpPost.setEntity(new UrlEncodedFormEntity(paramList, StandardCharsets.UTF_8));
}
return executeRequest(httpPost);
}
/**
* 執(zhí)行POST請(qǐng)求(JSON格式)
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doPostJson(String url, Map<String, String> headers) throws IOException {
return doPostJson(url, headers, null);
}
/**
* 執(zhí)行POST請(qǐng)求(JSON格式)
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @param jsonBody JSON請(qǐng)求體字符串
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doPostJson(String url, Map<String, String> headers, String jsonBody) throws IOException {
HttpPost httpPost = new HttpPost(url);
// 添加JSON請(qǐng)求頭
addJsonHeader(httpPost, headers);
// 添加自定義請(qǐng)求頭
setHeaders(httpPost, headers);
// 設(shè)置JSON請(qǐng)求體
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPost.setEntity(entity);
}
return executeRequest(httpPost);
}
/**
* 執(zhí)行PUT請(qǐng)求(JSON格式)
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @param jsonBody JSON請(qǐng)求體字符串
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doPut(String url, Map<String, String> headers, String jsonBody) throws IOException {
HttpPut httpPut = new HttpPut(url);
// 添加JSON請(qǐng)求頭
addJsonHeader(httpPut, headers);
// 添加自定義請(qǐng)求頭
setHeaders(httpPut, headers);
// 設(shè)置JSON請(qǐng)求體
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPut.setEntity(entity);
}
return executeRequest(httpPut);
}
/**
* 執(zhí)行DELETE請(qǐng)求
*
* @param url 請(qǐng)求地址
* @param headers 請(qǐng)求頭
* @return 響應(yīng)內(nèi)容字符串
*/
public static String doDelete(String url, Map<String, String> headers) throws IOException {
HttpDelete httpDelete = new HttpDelete(url);
// 設(shè)置請(qǐng)求頭
setHeaders(httpDelete, headers);
return executeRequest(httpDelete);
}
/**
* 創(chuàng)建帶超時(shí)配置的HttpClient
*
* @return HttpClient實(shí)例
*/
private static CloseableHttpClient createHttpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
}
/**
* 添加JSON請(qǐng)求頭
*
* @param httpRequest HTTP請(qǐng)求對(duì)象
* @param headers 請(qǐng)求頭
*/
private static void addJsonHeader(HttpRequestBase httpRequest, Map<String, String> headers) {
if (headers == null || !headers.containsKey("Content-Type")) {
httpRequest.addHeader("Content-Type", "application/json;charset=utf-8");
}
}
/**
* 設(shè)置請(qǐng)求頭
*
* @param httpRequest HTTP請(qǐng)求對(duì)象
* @param headers 請(qǐng)求頭
*/
private static void setHeaders(HttpRequestBase httpRequest, Map<String, String> headers) {
if (headers == null || headers.isEmpty()) {
return;
}
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpRequest.setHeader(entry.getKey(), entry.getValue());
}
}
/**
* 統(tǒng)一執(zhí)行請(qǐng)求并處理響應(yīng)
*
* @param httpRequest HTTP請(qǐng)求對(duì)象
* @return 響應(yīng)內(nèi)容字符串
*/
private static String executeRequest(HttpRequestBase httpRequest) throws IOException {
try (CloseableHttpClient httpClient = createHttpClient()) {
try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
return handleResponse(response);
}
}
}
/**
* 處理響應(yīng)結(jié)果
*
* @param response HTTP響應(yīng)對(duì)象
* @return 響應(yīng)內(nèi)容字符串
*/
private static String handleResponse(CloseableHttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("HTTP請(qǐng)求失敗,狀態(tài)碼:" + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
return null;
}
}
文章持續(xù)更新,歡迎關(guān)注微信公眾號(hào)「申城異鄉(xiāng)人」第一時(shí)間閱讀!
浙公網(wǎng)安備 33010602011771號(hào)