OkHttpUtils.java
6.61 KB
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
package com.huaheng.common.utils.http;
import com.google.gson.Gson;
import com.huaheng.common.constant.QuantityConstant;
import com.huaheng.framework.aspectj.ApiLogAspect;
import com.huaheng.framework.web.service.ConfigService;
import com.huaheng.pc.monitor.apilog.domain.ApiLog;
import com.huaheng.pc.system.config.domain.Config;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* OkHttp发送请求
* @author huaheng
* @Date 2022-5-30
*/
public class OkHttpUtils {
@Resource
private ConfigService configService;
private static final Logger log = LoggerFactory.getLogger(OkHttpUtils.class);
/**
* 最大连接时间
*/
public final static int CONNECTION_TIMEOUT = 30;
/**
* JSON格式
*/
public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
/**
* OkHTTP线程池最大空闲线程数
*/
public final static int MAX_IDLE_CONNECTIONS = 100;
/**
* OkHTTP线程池空闲线程存活时间
*/
public final static long KEEP_ALIVE_DURATION = 30L;
private static final String CONTENT_TYPE = "Content-Type";
/**
* client
* 配置重试
*/
private final static OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder()
.readTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.SECONDS)
.connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, KEEP_ALIVE_DURATION, TimeUnit.MINUTES))
.build();
private static final Gson GSON = new Gson();
/**
* 向指定 URL 发送GET方法的请求
*
* @param url 发送请求的 URL
//* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendGet(String url,String param)
{
//headers 请求头
Map<String, String> headers=new HashMap<>();
//请求URI
String urlNameString = url + "?" + param;
Request.Builder builder = new Request.Builder();
buildHeader(builder, headers);
Request request = builder.url(urlNameString).get().build();
Response response = null;
try {
response = HTTP_CLIENT.newCall(request).execute();
if (response.isSuccessful() && Objects.nonNull(response.body())) {
String result = response.body().string();
log.info("执行get请求, url: {} 成功,返回数据: {}", url, result);
return result;
}
} catch (IOException e) {
log.error("执行get请求,url: {} 失败!", url, e);
}
return "";
}
/**
* 向指定 URL 发送POST方法的请求
*
* @param url 发送请求的 URL
// * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param){
FormBody.Builder builder = new FormBody.Builder();
String urlNameString = url + "?" + param;
FormBody body = builder.build();
Request request = new Request
.Builder()
.url(urlNameString)
.post(body)
.build();
Response response = null;
try {
response = HTTP_CLIENT.newCall(request).execute();
//调用成功
if (response.isSuccessful() && response.body() != null) {
return response.body().string();
}
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
public static String bodypost(String strURL, String json) {
return bodypost(strURL, json, "");
}
//此方法是将参数以body形式发送post请求
public static String bodypost(String strURL, String json, String sessionId) {
ApiLog apiLog = null;
// using above json body as a input to post API call
RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
//headers 请求头
Map<String, String> headers =new HashMap<>();
headers.put("Accept","application/json");// 设置接收数据的格式
headers.put("Content-Type","application/json");// 设置发送数据的格式
headers.put("kdservice-sessionid", sessionId);// 设置发送数据的格式
Request.Builder builder = new Request.Builder();
buildHeader(builder, headers);
Request request = builder.url(strURL).post(body).build();
Response response = null;
String result=null;
try {
apiLog = ApiLogAspect.initApiLog(request, json);
response = HTTP_CLIENT.newCall(request).execute();
if (response.isSuccessful() && Objects.nonNull(response.body())) {
result = response.body().string();
log.info("执行post请求,url: {}, header: {} ,参数: {} 成功,返回结果: {}", strURL, headers, json, result);
}
} catch (IOException e) {
ApiLogAspect.setApiLogException(apiLog, e);
log.error("执行post请求,url: {},参数: {} 失败!", strURL, json, e);
} finally {
ApiLogAspect.finishApiLog(apiLog, response, result);
}
return result;
}
/**
* 设置请求头
*
* @param builder .
* @param headers 请求头
*/
private static void buildHeader(Request.Builder builder, Map<String, String> headers) {
if (Objects.nonNull(headers) && headers.size() > 0) {
headers.forEach((k, v) -> {
if (Objects.nonNull(k) && Objects.nonNull(v)) {
builder.addHeader(k, v);
}
});
}
}
/**
* 支持嵌套泛型的post请求。
* <pre>
* Type type = new TypeToken<Results<User>>() {}.getType();
* <pre/>
*
* @param url 链接
* @param json 请求json
* @param type 嵌套泛型
* @return 响应对象, 可进行强转。
*/
public static <T> T post(String url, String json, Type type) {
String result = bodypost(url, json);
if (Objects.nonNull(result) && Objects.nonNull(type)) {
return GSON.fromJson(result, type);
}
return null;
}
}