首页 归档 关于 文件 Github
×

OkHttp3 工具类

2024-06-13 13:52:25
J-Tools
  • OkHttp3
本文总阅读量(次):
本文字数统计(字):693
本文阅读时长(分):3

对请求的封装:可以进行https请求,重试次数,

依赖

1
2
3
4
5
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.9.1</version>
</dependency>

代码

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
package com.demon.util;

import okhttp3.*;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
* author :demon
* date :2023 2023/3/5 13:28
* desc :
*/
public class OkHttpClientUtil {

public static String post(Headers.Builder headerBuilder, String url, String content) throws Exception {
// 执行POST(body)请求 - > 请问完成后 自动关闭连接
try (Response response = getOkHttpClient()
.newCall(new Request.Builder()
.url(url)
.headers(headerBuilder.build())
.post(RequestBody.create(MediaType.parse("application/json;charset=utf-8"), content))
.build()).execute()) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
System.out.println("响应的Code:" + response.code());
if (body != null) {
String bodyString = body.string();
System.out.println("响应的内容:" + bodyString);
return bodyString;
}
throw new Exception("返回内容为空");
} else {
throw new Exception("请求错误,response code:" + response.code());
}
} catch (IOException e) {
throw new IOException(e);
}
}

public static InputStream downloadFile(String url) throws IOException, NoSuchAlgorithmException, KeyManagementException {
// 发起请求得到请求结果
Response response = getOkHttpClient().newCall(new Request.Builder().url(url).get().build()).execute();
// 获取请求结果
ResponseBody responseBody = response.body();
if (null != responseBody) {
// 获取文件后缀类型 可以使用 responseBody.contentType() 获取 ContentType,我这边知道这个url文件的类型
// 获取请求结果输入流
return responseBody.byteStream();
}
response.close();
return null;
}

private static OkHttpClient getOkHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
return new OkHttpClient.Builder()
// 设置连接时间10分钟 - >三次握手 + SSL建立耗时
.connectTimeout(60 * 10, TimeUnit.SECONDS)
// 设置写入时间60秒
.writeTimeout(60, TimeUnit.SECONDS)
// 设置读取时间60秒
.readTimeout(60, TimeUnit.SECONDS)
// 添加信任HTTPS请求
.sslSocketFactory(sslSocketFactory(), x509TrustManager())
// 过滤器,设置最大重试次数
.addInterceptor(new OkHttpInterceptor(3))
// 不自动重连
.retryOnConnectionFailure(false).build();
}


private static SSLSocketFactory sslSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
// 信任任何链接
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
return sslContext.getSocketFactory();
}

private static X509TrustManager x509TrustManager() {
return new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}

@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
}


private static class OkHttpInterceptor implements Interceptor {

// 最大重试次数
private int maxRetry;

OkHttpInterceptor(int maxRetry) {
this.maxRetry = maxRetry;
}

@SuppressWarnings("NullableProblems")
@Override
public Response intercept(Chain chain) {
/* 递归 4次下发请求,如果仍然失败 则返回 null ,但是 intercept must not return null.
* 返回 null 会报 IllegalStateException 异常
*/
return retry(chain, 0);
}

private Response retry(Chain chain, int retryCount) {
Request request = chain.request();
Response response = null;
try {
System.out.println("第" + (retryCount + 1) + "次执行HTTP请求···");
response = chain.proceed(request);
} catch (Exception e) {
if (maxRetry > retryCount) {
return retry(chain, retryCount + 1);
}
}
return response;
}
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
public void toTest() {
JSONObject json = new JSONObject();
json.put("jobId", "999999999");
try {
String post = OkHttpClientUtil.post(
new Headers.Builder().set("Content-Type", "application-json").set("API-KEY", "1234567890"),
"https://www.baidu.com/",
json.toJSONString());
System.out.println(post);
} catch (Exception e) {
e.printStackTrace();
}
}
完
K8S v1.20.6 容器之问题
zxing开发之二维码

本文标题:OkHttp3 工具类

文章作者:十二

发布时间:2024-06-13 13:52:25

最后更新:2024-08-05 14:35:18

原始链接:https://www.zhuqiaolun.com/2024/06/1718257945709/1718257945709/

许可协议:署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

头像

十二

我想起那天夕阳下的奔跑,那是我逝去的青春。

分类

  • Blog4
  • ElasticSearch13
  • Freemarker2
  • Git2
  • Go-FastDfs2
  • IDEA2
  • J-Package6
  • J-Tools21
  • Java2
  • JavaFx3
  • Kafka4
  • Linux2
  • Logger5
  • Maven5
  • MyBatis6
  • MyCat3
  • MySql2
  • Nginx5
  • OceanBase1
  • RabbitMq4
  • Redis6
  • SVN1
  • SpringBoot11
  • Tomcat6
  • WebService2
  • Windows2
  • kubernetes10

归档

  • 二月 20251
  • 十二月 20244
  • 八月 202416
  • 六月 20241
  • 九月 20231
  • 八月 20231
  • 七月 20232
  • 八月 20222
  • 三月 202214
  • 二月 20224
  • 十一月 20211
  • 七月 20215
  • 六月 20213
  • 五月 20213
  • 四月 20211
  • 三月 202116
  • 二月 20212
  • 一月 20211
  • 十一月 202014
  • 十月 20201
  • 九月 202014
  • 八月 20205
  • 七月 20204
  • 六月 20208
  • 五月 20208

作品

我的微信 我的文件

网站信息

本站运行时间统计: 载入中...
本站文章字数统计:96.9k
本站文章数量统计:132
© 2025 十二  |  鄂ICP备18019781号-1  |  鄂公网安备42118202000044号
驱动于 Hexo  | 主题 antiquity  |  不蒜子告之 阁下是第个访客
首页 归档 关于 文件 Github