1. 引入httpclient依赖
首先,需要确认项目中是否已引入过httpclient依赖,如果没有引入过,需要在pom.xml中添加以下代码引入httpclient依赖:
xml
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
2. 发送GET请求
2.1 发送GET请求(无参数)
java
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 发送GET请求(带参数)
第一种方法是直接在url上拼接上参数,如下所示:
java
HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");
第二种方法是使用URIBuilder添加参数,如下所示:
java
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. 发送POST请求
3.1 发送POST请求(无参数)
java
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 发送POST请求(带参数、form表单方式)
java
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 发送POST请求(带参数、json方式)
java
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. 发送PUT请求
4.1 发送PUT请求(无参数)
java
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 发送PUT请求(带参数、form表单方式)
java
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 发送PUT请求(带参数、json方式)
java
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. 发送DELETE请求
5.1 发送DELETE请求(无参数)
java
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. 添加请求头
一般情况下,请求第三方接口都需要签名、时间戳等请求头,以POST请求为例,添加请求头的代码如下所示:
java
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
httpPost.setHeader("signature", "3045022100875efcef9eb54626bb0168a6baa7c61265d0001d49243f");
httpPost.setHeader("timestamp", String.valueOf(System.currentTimeMillis()));
GET请求、PUT请求、DELETE请求添加请求头的方法同上。
7. 超时时间设置
如果需要自定义HTTP请求的连接超时时间和数据传输超时时间,代码如下所示(以POST请求为例):
java
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(requestConfig);
GET请求、PUT请求、DELETE请求设置超时时间的方法同上。
8.工具类封装
完整的工具类代码如下所示:
java
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 {
/**
* 连接建立超时时间(单位:毫秒)
*/
private static final int CONNECT_TIMEOUT = 5000;
/**
* 数据传输超时时间(单位:毫秒)
*/
private static final int SOCKET_TIMEOUT = 10000;
/**
* 执行GET请求
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doGet(String url, Map<String, String> headers) throws IOException {
HttpGet httpGet = new HttpGet(url);
// 设置请求头
setHeaders(httpGet, headers);
return executeRequest(httpGet);
}
/**
* 执行GET请求
*
* @param url 请求地址
* @param headers 请求头
* @param params 请求参数
* @return 响应内容字符串
*/
public static String doGet(String url, Map<String, String> headers, Map<String, String> params) throws IOException, URISyntaxException {
URIBuilder uriBuilder = new URIBuilder(url);
// 设置请求参数
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());
// 设置请求头
setHeaders(httpGet, headers);
return executeRequest(httpGet);
}
/**
* 执行POST请求(表单方式)
*
* @param url 请求地址
* @return 响应内容字符串
*/
public static String doPost(String url) throws IOException {
return doPost(url, null, null);
}
/**
* 执行POST请求(表单方式)
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doPost(String url, Map<String, String> headers) throws IOException {
return doPost(url, headers, null);
}
/**
* 执行POST请求(表单方式)
*
* @param url 请求地址
* @param headers 请求头
* @param params 请求参数
* @return 响应内容字符串
*/
public static String doPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
HttpPost httpPost = new HttpPost(url);
// 设置请求头
setHeaders(httpPost, headers);
// 构建表单参数
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);
}
/**
* 执行POST请求(JSON格式)
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doPostJson(String url, Map<String, String> headers) throws IOException {
return doPostJson(url, headers, null);
}
/**
* 执行POST请求(JSON格式)
*
* @param url 请求地址
* @param headers 请求头
* @param jsonBody JSON请求体字符串
* @return 响应内容字符串
*/
public static String doPostJson(String url, Map<String, String> headers, String jsonBody) throws IOException {
HttpPost httpPost = new HttpPost(url);
// 添加JSON请求头
addJsonHeader(httpPost, headers);
// 添加自定义请求头
setHeaders(httpPost, headers);
// 设置JSON请求体
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPost.setEntity(entity);
}
return executeRequest(httpPost);
}
/**
* 执行PUT请求(JSON格式)
*
* @param url 请求地址
* @param headers 请求头
* @param jsonBody JSON请求体字符串
* @return 响应内容字符串
*/
public static String doPut(String url, Map<String, String> headers, String jsonBody) throws IOException {
HttpPut httpPut = new HttpPut(url);
// 添加JSON请求头
addJsonHeader(httpPut, headers);
// 添加自定义请求头
setHeaders(httpPut, headers);
// 设置JSON请求体
if (jsonBody != null) {
StringEntity entity = new StringEntity(jsonBody,
ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
httpPut.setEntity(entity);
}
return executeRequest(httpPut);
}
/**
* 执行DELETE请求
*
* @param url 请求地址
* @param headers 请求头
* @return 响应内容字符串
*/
public static String doDelete(String url, Map<String, String> headers) throws IOException {
HttpDelete httpDelete = new HttpDelete(url);
// 设置请求头
setHeaders(httpDelete, headers);
return executeRequest(httpDelete);
}
/**
* 创建带超时配置的HttpClient
*
* @return HttpClient实例
*/
private static CloseableHttpClient createHttpClient() {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONNECT_TIMEOUT)
.setSocketTimeout(SOCKET_TIMEOUT)
.build();
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.build();
}
/**
* 添加JSON请求头
*
* @param httpRequest HTTP请求对象
* @param headers 请求头
*/
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");
}
}
/**
* 设置请求头
*
* @param httpRequest HTTP请求对象
* @param headers 请求头
*/
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());
}
}
/**
* 统一执行请求并处理响应
*
* @param httpRequest HTTP请求对象
* @return 响应内容字符串
*/
private static String executeRequest(HttpRequestBase httpRequest) throws IOException {
try (CloseableHttpClient httpClient = createHttpClient()) {
try (CloseableHttpResponse response = httpClient.execute(httpRequest)) {
return handleResponse(response);
}
}
}
/**
* 处理响应结果
*
* @param response HTTP响应对象
* @return 响应内容字符串
*/
private static String handleResponse(CloseableHttpResponse response) throws IOException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
throw new RuntimeException("HTTP请求失败,状态码:" + statusCode);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
return null;
}
}