• 主页
  • 读书笔记
  • 备案号:滇ICP备19009238号
所有文章 其他站点 关于我

  • 主页
  • 读书笔记
  • 备案号:滇ICP备19009238号

HTTPClient工具类实现

2023-04-07

HTTPClient工具类实现

GET请求带Entity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

import java.net.URI;

/**
* @author 曳戈泰尔
* @version 1.0
* @description 定义一个带body的GET请求 继承 HttpEntityEnclosingRequestBase
* @date 2023/3/29 4:04 PM
*/
public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {

private static final String METHOD_NAME = "GET";

@Override
public String getMethod() {
return METHOD_NAME;
}

public HttpGetWithEntity() {
super();
}

public HttpGetWithEntity(final URI uri) {
super();
setURI(uri);
}

HttpGetWithEntity(final String uri) {
super();
setURI(URI.create(uri));
}
}

一般HTTP请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import lombok.extern.slf4j.Slf4j;
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.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.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.URI;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* @author 曳戈泰尔
* @version 1.0
* @description HTTP请求单元类
* @date 2023/3/13 2:09 PM
*/
@Slf4j
public class HttpClientHelper {

/** 请求配置 */
private static RequestConfig requestConfig = null;

private HttpClientHelper() {
// 设置http的状态参数
requestConfig =
RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
// TODO 补充其他配置
}

/**
* 有参数的GET请求
*
* <p>Params参数
*
* @param url
* @param param map参数
* @return
*/
public static String doGet(String url, Map<String, String> param) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

String resultString = null;
CloseableHttpResponse response = null;

try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();

// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig);

// 执行请求
response = httpClient.execute(httpGet);

// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
log.error("HttpClient GET请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient GET请求关闭流失败,原因:{}", e.getMessage());
}
}

return resultString;
}

/**
* 有参数的GET请求
*
* <p>Params参数
*
* <p>带请求Header
*
* @param url
* @param param map参数
* @return
*/
public static String doGet(String url, Map<String, String> param, String keyHeader) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

String resultString = null;
CloseableHttpResponse response = null;

try {
// 创建uri
URIBuilder builder = new URIBuilder(url);
if (param != null) {
for (String key : param.keySet()) {
builder.addParameter(key, param.get(key));
}
}
URI uri = builder.build();

// 创建http GET请求
HttpGet httpGet = new HttpGet(uri);
httpGet.setConfig(requestConfig);

// 设置请求头
httpGet.setHeader("x-api-key", keyHeader);

// 执行请求
response = httpClient.execute(httpGet);

// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
log.error("HttpClient GET请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient GET请求关闭流失败,原因:{}", e.getMessage());
}
}

return resultString;
}

/**
* 带Header的请求
*
* <p>JSON参数
*
* @param url
* @param json
* @param keyHeader
* @return
*/
public static String doGet(String url, String json, String keyHeader) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

String resultString = null;
CloseableHttpResponse response = null;

try {
// 创建http GET请求
HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
httpGetWithEntity.setConfig(requestConfig);

// 设置Header
httpGetWithEntity.setHeader("x-api-key", keyHeader);

// 设置请求参数
HttpEntity httpEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpGetWithEntity.setEntity(httpEntity);

// 执行请求
response = httpClient.execute(httpGetWithEntity);

// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
log.error("HttpClient GET请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient GET请求关闭流失败,原因:{}", e.getMessage());
}
}

return resultString;
}

/**
* 无参数的GET请求
*
* @param url
* @return
*/
public static String doGet(String url) {
return doGet(url, null);
}

/**
* 有参数的POST请求
*
* <p>form-data参数
*
* @param url
* @param param Map参数
* @return
*/
public static String doPost(String url, Map<String, Object> param) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;
String resultString = null;

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);

// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, (String) param.get(key)));
}

// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}

// 执行http请求
response = httpClient.execute(httpPost);

// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}

} catch (Exception e) {
log.error("HttpClient POST请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient POST请求关闭流失败,原因:{}", e.getMessage());
}
}

return resultString;
}

/**
* 无参数的POST请求
*
* @param url
* @return
*/
public static String doPost(String url) {
return doPost(url, null);
}

/**
* 有参数的POST请求
*
* <p>Json参数
*
* @param url
* @param json
* @return
*/
public static String doPostJson(String url, String json) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;
String resultString = null;

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);

// 创建请求内容
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

StringEntity entity = new StringEntity(json);
entity.setContentType("application/json;charset=utf-8");
httpPost.setEntity(entity);

// 执行http请求
response = httpClient.execute(httpPost);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
log.error("HttpClient POST请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient POST请求关闭流失败,原因:{}", e.getMessage());
}
}

return resultString;
}

/**
* 有参数的POST请求
*
* <p>JOSN参数
*
* <p>增加请求Header
*
* @param url
* @param json
* @param keyHeader
* @return
* @throws Exception
*/
public static String doPostJson(String url, String json, String keyHeader) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;
String resultString = null;

try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
httpPost.setConfig(requestConfig);

// 创建请求内容
httpPost.setHeader("Connection", "Keep-Alive");
httpPost.setHeader("Content-Type", "application/json;charset=utf-8");

// 设置鉴权请求头
httpPost.setHeader("x-api-key", keyHeader);

// 创建请求内容
StringEntity entity = new StringEntity(json);
entity.setContentType("application/json;charset=utf-8");
httpPost.setEntity(entity);

// 执行http请求
response = httpClient.execute(httpPost);

if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
resultString = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
}
} catch (Exception e) {
log.error("HttpClient POST请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient POST请求关闭流失败,原因:{}", e.getMessage());
}
}

return resultString;
}
}

PUT文件请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
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.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;

/**
* @author 曳戈泰尔
* @version 1.0
* @description HTTP PUT请求 Helper
* @date 2023/3/29 1:10 AM
*/
@Slf4j
public class HttpPutHelper {

/** 请求配置 */
private static RequestConfig requestConfig = null;

private HttpPutHelper() {
// 设置http的状态参数
requestConfig =
RequestConfig.custom()
.setSocketTimeout(5000)
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.build();
// TODO 补充其他配置
}

public static Boolean doAwsS3Put(String s3Url, String uploadImageUrl) {

// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();

CloseableHttpResponse response = null;

// 定义返回结果状态
boolean result = false;

try {
// 创建http PUT请求
HttpPut httpPut = new HttpPut(s3Url);
httpPut.setConfig(requestConfig);

// 设置请求头
httpPut.addHeader("Content-Type", "text/plain");

// 设置请求体
URL url = new URL(uploadImageUrl);
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
InputStreamEntity inputStreamEntity =
new InputStreamEntity(in, ContentType.APPLICATION_OCTET_STREAM);
// 通过BufferedHttpEntity包装输入流,防止流被关闭
BufferedHttpEntity bufEntity = new BufferedHttpEntity(inputStreamEntity);
httpPut.setEntity(bufEntity);

// 执行请求
response = httpClient.execute(httpPut);

// 判断返回状态是否为200
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
log.info(
"HttpClient PUT请求成功,返回数据:{}",
EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8));

result = true;
}
} catch (Exception e) {
log.error("HttpClient PUT请求发生异常,原因:{}", e.getMessage());
} finally {
try {
if (response != null) {
response.close();
}
if (httpClient != null) {
httpClient.close();
}
} catch (IOException e) {
log.error("HttpClient PUT请求关闭流失败,原因:{}", e.getMessage());
}
}

return result;
}
}

  • HTTP
SpringBoot实现输入输出日志打印
微信小程序WebView跳转wxJS实现签名
  1. 1. GET请求带Entity
  2. 2. 一般HTTP请求
  3. 3. PUT文件请求
© 2023 曳戈泰尔
Hexo Theme Yilia by Litten
  • 所有文章
  • 其他站点
  • 关于我

tag:

  • SHA256
  • AI换脸
  • VITS
  • APM
  • Anaconda
  • AnsibleAWX
  • ArrayList
  • Bean
  • BigDecimal
  • Blender three.js
  • API开放接口
  • xmlRPC
  • Ice
  • MySQL
  • BeanUtils
  • Tomcat
  • Caffeine
  • gradle
  • Docker
  • jdk
  • maven
  • JDK
  • localtime
  • Minio
  • PostgreSQL
  • RT_Linux
  • kafka
  • geany
  • CentOS
  • Elasticsearch
  • Node
  • FastDFS
  • Nginx
  • CompletableFutures
  • CompletableFuture
  • CountDownLatch
  • queue
  • Conflux
  • DefaultIdentifierGenerator
  • gdb
  • Deepin
  • Deferred
  • 自动化部署
  • Nacos
  • Redis
  • RocketMQ
  • docker-compose
  • docker日志
  • Docker部署
  • Drools
  • Vue
  • 持有者作为调用者
  • Error
  • ES
  • 签名上链
  • FISCO
  • Prometheus-Grafana-nodeExporter
  • FISCO开放平台
  • 解析input
  • ForkJoinPool
  • GateWay
  • Git
  • GeoServer
  • GitLab
  • Gradle
  • Spring
  • Gitlab
  • HTTP
  • Hexo GitHub-Pages
  • HttpUtil
  • IDEA
  • Gson
  • 热部署
  • HttpClientUtil
  • 搜索
  • Stream
  • foreach
  • Graphics2D
  • Synchronized
  • 循环
  • Integer
  • base64
  • JAVA
  • Excel
  • openID
  • NowTime
  • MD5
  • 字节流
  • 手机号
  • 支付宝
  • Object
  • 行政区划
  • 序列化
  • telnet
  • 枚举
  • 限流
  • 配置文件
  • 规则执行器
  • cmd
  • netty websocket
  • JAVE2
  • 线程池
  • 分治
  • JMH
  • JVM
  • Jenkins
  • Java调用AI输入输出
  • JWT
  • Kindle
  • Knif4j
  • jar
  • UDP
  • SonarQube
  • 部署
  • Ansible
  • IP
  • socket
  • List排序
  • MQ
  • MapStruct
  • Maven
  • MyBatis-Plus
  • MyBatis
  • 跳板机
  • event
  • trigger
  • 全文索引
  • 扣费 线程安全
  • MybatisPlus
  • LambdaQueryWrapper
  • Navicat
  • Explain
  • 私人助理
  • nacos
  • Nexus
  • WebSocket
  • OSS
  • OkHttpClient
  • OA
  • PicGo
  • 可视化监控
  • Optional
  • SpringBoot
  • 关键词
  • TSV
  • 性能指标
  • json
  • Pycharm
  • 文件夹遍历
  • TCP
  • Qt
  • QueryWrapper
  • Quartz
  • RSA
  • RabbitMQ
  • RateLimiter
  • Redisson
  • 阻塞等待锁
  • ZSET
  • incr
  • 频率限制
  • SAE
  • RESTful API
  • SCP
  • RuoYi
  • SM3
  • SKU
  • SQL
  • SQL前n天
  • SSL
  • Shell脚本自动化
  • Sleuth
  • Socket
  • PageHelper
  • Solidity
  • gateway
  • Batch
  • Spring Boot
  • build.gradle
  • Schedule
  • 循环重试
  • Undertow
  • 多筛选
  • IPFS
  • Jasypt
  • logback
  • 加解密
  • 幂等性
  • Result
  • log
  • Mail
  • 滑块
  • Druid
  • knife4j
  • 注入
  • Full Lite
  • 权限
  • 跨域访问
  • starter
  • 防刷
  • XSS
  • Event
  • 多数据库
  • Scheduled
  • yml
  • Async
  • AOP
  • CurrentUser
  • AutoGenerator
  • netty
  • Openfeign
  • Sentinel
  • Shiro
  • Swagger
  • XMLRPC
  • captcha
  • OAuth
  • 文件上传
  • 验证码登录
  • Response
  • Exception
  • 文件下载
  • 自定义注解
  • Thread
  • 观察者
  • 音视频
  • dll
  • StopWatch
  • String
  • Transactional
  • ThreadLocal
  • TLS
  • 挂载
  • VMware
  • VPN
  • VSAT
  • VScode
  • VS
  • Valid
  • 二维码
  • three.js
  • ECDSA
  • Tornado
  • WorkBench
  • VxWorks
  • select
  • taskSpawn
  • WPS
  • WeBase
  • JavaScript
  • COOKIE
  • 消息推送
  • 开启启动
  • VxWorks WorkBench
  • XStream
  • ab
  • appId appKey
  • printStackTrace
  • gitlab
  • excel2word
  • git
  • 经纬度
  • isNull isEmpty isBlank
  • mybatisplus
  • SSH
  • nohup日志
  • phpstudy
  • npm
  • 图片
  • nginx
  • url
  • xml
  • 去背景
  • 提取学号
  • 一键登录
  • xxl-job
  • 并发
  • 接口
  • 一致性HASH
  • 责任链
  • 两层请求体
  • 二次支付
  • 个人支付
  • 设计模式
  • 代理
  • MERGE
  • 保存MultipartFile
  • PDF
  • 链间数据迁移
  • session
  • 鉴权
  • 证书生成
  • 单例
  • 压测
  • shell
  • 发布Jar
  • sms
  • 升级代理合约
  • 支付
  • 图片转PDF
  • 拍平JSON
  • SSO
  • property
  • 内容安全
  • 循环分页
  • crontab
  • 日志清理
  • 实名
  • 绩效
  • 读书笔记
  • 歌词识别
  • component初始化
  • 抽奖
  • 数据脱敏
  • 验证码
  • 网络攻防
  • 慢排查
  • Native支付
  • 裁剪字符串
  • WebView
  • 文本折叠
  • 上拉加载数据
  • 弹窗输入框
  • 图片裁剪
  • banner
  • 局部刷新
  • 弹窗
  • StorageSync
  • 标签id值
  • openId
  • 角标
  • globalData
  • url传值
  • Feign
  • 懒加载
  • 订阅消息
  • 设备交接
  • 提取txt 提取word
  • 回调
  • 支付超时
  • Assert
  • 乐观锁
  • 服务器
  • 监控
  • 运维
  • 方案
  • Enum
  • 测试
  • 校招
  • 死锁
  • 兑换码
  • 订单
  • 余额扣减
  • sku gson
  • 电商
  • 短信验证码
  • 伏羲PDF
  • 秒杀
  • 后台
  • 不可破解key
  • 排查
  • 线程安全 Map List
  • 上下电
  • CRUD拆分的宽表
  • ip2region
  • 行政
  • 文件校验FileSize
  • ParameterMap
  • EventBus
  • 微信手机号
  • 购买掉单
  • resources
  • 音频时长
  • IDCardUtils
  • Ghelper
  • Forest
  • 邀请
  • 过滤器 拦截器
  • 通信
  • Retry
  • 人脸融合
  • 时间差
  • 短信
  • 集合
  • 长安链

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

  • 区块链
  • GPT
  • gitee1
  • gitee2
  • github
  • Other
徘徊在原子与字节的边缘

将更好的自己呈现给世界



修心至要,事上磨练

一蓑衣,一壶酒,一曲长歌,一剑天涯

见自己,见天地,见众生