1. 引入httpclient依赖

首先,需要确认项目中是否已引入过httpclient依赖,如果没有引入过,需要在pom.xml中添加以下代码引入httpclient依赖:

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

2. 发送GET请求

2.1 发送GET请求(无参数)

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上拼接上参数,如下所示:

HttpGet httpGet = new HttpGet("https://www.example.com/getDataList?pageIndex=1&pageSize=20");

第二种方法是使用URIBuilder添加参数,如下所示:

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请求(无参数)

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表单方式)

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方式)

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请求(无参数)

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表单方式)

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方式)

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请求(无参数)

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请求为例,添加请求头的代码如下所示:

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请求为例):

RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(5000)
.setSocketTimeout(10000)
.build();
httpPost.setConfig(requestConfig);

GET请求、PUT请求、DELETE请求设置超时时间的方法同上。

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 {
/**
* 连接建立超时时间(单位:毫秒)
*/
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;
}
}

HttpClient使用方法总结及工具类封装的更多相关文章

  1. JavaFx 生成二维码工具类封装

    原文地址: JavaFx 生成二维码工具类封装 - Stars-One的杂货小窝 之前星之音乐下载器有需要生成二维码功能,当时用的是一个开源库来实现的,但是没过多久,发现那个库依赖太多,有个http- ...

  2. Redis操作Set工具类封装,Java Redis Set命令封装

    Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...

  3. Redis操作List工具类封装,Java Redis List命令封装

    Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...

  4. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  5. (转载) 百度地图工具类封装(包括定位,附近、城市、范围poi检索,反地理编码)

    目录视图 摘要视图 订阅 赠书 | 异步2周年,技术图书免费选      程序员8月书讯      项目管理+代码托管+文档协作,开发更流畅 百度地图工具类封装(包括定位,附近.城市.范围poi检索, ...

  6. 小D课堂 - 零基础入门SpringBoot2.X到实战_第9节 SpringBoot2.x整合Redis实战_40、Redis工具类封装讲解和实战

    笔记 4.Redis工具类封装讲解和实战     简介:高效开发方式 Redis工具类封装讲解和实战         1.常用客户端 https://redisdesktop.com/download ...

  7. flink---实时项目--day02-----1. 解析参数工具类 2. Flink工具类封装 3. 日志采集架构图 4. 测流输出 5. 将kafka中数据写入HDFS 6 KafkaProducer的使用 7 练习

    1. 解析参数工具类(ParameterTool) 该类提供了从不同数据源读取和解析程序参数的简单实用方法,其解析args时,只能支持单只参数. 用来解析main方法传入参数的工具类 public c ...

  8. 关于TornadoFx和Android的全局配置工具类封装实现及思路解析

    原文地址: 关于TornadoFx和Android的全局配置工具类封装实现及思路解析 - Stars-One的杂货小窝 目前个人开发软件存在设置页面,可以让用户自定义些设置,但我发现,存储数据的代码逻 ...

  9. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

  10. Android Sqlite 工具类封装

    鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用. 该封装类主要支持一下功能 支持多用户数据储存 支持 Sqlite数据库升级 支持传入 Sql 语句建表 支持 SQLit ...

随机推荐

  1. c# Moq Ref/out 参数

    public interface IService { void DoSomething(ref string a); void DoSomething2(out string a); } [Test ...

  2. UWP Shadow 阴影

    参考文字: https://mtaulty.com/2016/08/10/windows-10-uwp-and-composition-light-and-shade/ <Grid Backgr ...

  3. linux:计划任务

    at 计划执行一次性任务 at  + time 表示方法: atq  -c:查看目前等待执行的任务 atrm  任务编号 :删除at任务  [root账户才能删除,其他用户只能查询] crontab ...

  4. 搭建个人AI知识库:RAG与本地模型实践指南

    引言 你是否想过拥有一个私人订制的AI助手,能够随时为你提供最个性化的信息?本文将带你一步步搭建一个基于本地模型和RAG技术的个人知识库. 搭建本地模型 环境 os: archlinux 内存: 32 ...

  5. RocketMQ原理—4.消息读写的性能优化

    大纲 1.Producer基于队列的消息分发机制 2.Producer基于Hash的有序消息分发 3.Broker如何实现高并发消息数据写入 4.RocketMQ读写队列的运作原理分析 5.Consu ...

  6. 第4章 C#的高级特性

    第4章 C#的高级特性 4.1 委托 4.1.2 多播委托 对值为 null 的委托变量进行 + ​或 += ​操作,等价于为变量指定一个新值: SomeDelegate d = null; d += ...

  7. 边缘计算与MEC浅谈

    本文分享自天翼云开发者社区<边缘计算与MEC浅谈>,作者:y****n 一.什么是边缘计算 边缘计算是在靠近物或数据源头的网络边缘侧,通过融合网络.计算.存储.应用核心能力的分布式开放平台 ...

  8. Xshell不可以删除,退格^H

    文件→属性→终端→键盘,把delete和backspace序列改为 ASCII 127即可.

  9. SCCPC2024 游记

    打了一堆板子,一个都没用上. 队友:zhicheng,nityacke 开场发现 H 是签到,NIT 签了.然后盯 F(圆向某个方向运动,问存不存在一个时刻使得全在长方形之内),发现不外乎一堆二次方程 ...

  10. FreeSql学习笔记——5.删除

    前言   对于FreeSql来说,删除的支持并不强大,只有在Where条件不为空的时候才执行,否则返回0或默认值,不执行删除操作:     语法   fsql.Delete<Class>( ...