OkhttpUtils 工具类

记录一下OkhttpUtils工具类

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

/**
* Created by IntelliJ IDEA.
* User: 贝先 [ Cason mo ]
* Date: 2022/5/20
* Time: 10:56
*/
public class OkHttpUtils {

private static final Logger logger = LoggerFactory.getLogger(OkHttpUtils.class);
public int readTimeout = 100;
public int connectTimeout = 60;
public int writeTimeout = 60;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
private static final byte[] LOCKER = new byte[0];
private static OkHttpUtils mInstance;
private OkHttpClient mOkHttpClient;

public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}

public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}

public void setWriteTimeout(int writeTimeout) {
this.writeTimeout = writeTimeout;
}


/**
* 自定义网络回调接口
*/
public interface NetCall {
void success(Call call, Response response) throws IOException;

void failed(Call call, IOException e);
}

private OkHttpUtils() {
okhttp3.OkHttpClient.Builder clientBuilder = new okhttp3.OkHttpClient.Builder();
clientBuilder.readTimeout(readTimeout, TimeUnit.SECONDS);//读取超时
clientBuilder.connectTimeout(connectTimeout, TimeUnit.SECONDS);//连接超时
clientBuilder.writeTimeout(writeTimeout, TimeUnit.SECONDS);//写入超时
clientBuilder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
mOkHttpClient = clientBuilder.build();
}

public static OkHttpUtils newInstance() {
return new OkHttpUtils();
}

/**
* 单例模式获取OkHttpUtil
*
* @return
*/
public static OkHttpUtils getInstance() {
if (mInstance == null) {
synchronized (LOCKER) {
if (mInstance == null) {
mInstance = new OkHttpUtils();
}
}
}
return mInstance;
}

public Response get(String url, Map<String, String> params, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
Request.Builder builder = new Request.Builder();
UriBuilder uriBuilder = UriBuilder.fromUri(url);
if (params != null) {
for (Map.Entry<String, String> param : params.entrySet()) {
if (StringUtils.isNotBlank(param.getKey())) {
uriBuilder.queryParam(param.getKey(), param.getValue());
}
}
}
Request request = builder.get().url(uriBuilder.build().toString()).headers(headers).build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
Call call = mOkHttpClient.newCall(request);
return call.execute();
}


public <T> Response post(String url, T t, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.post(RequestBody.create(JSON, "")).url(url).headers(headers);
if (t != null) {
RequestBody body = RequestBody.create(JSON, JsonUtils.toJSONString(t));
requestBuilder.post(body);
}
Request request = requestBuilder.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
Call call = mOkHttpClient.newCall(request);
return call.execute();
}

public <T> Response patch(String url, T t, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.patch(RequestBody.create(JSON, "")).url(url).headers(headers);
if (t != null) {
RequestBody body = RequestBody.create(JSON, JsonUtils.toJSONString(t));
requestBuilder.patch(body);
}
Request request = requestBuilder.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
Call call = mOkHttpClient.newCall(request);
return call.execute();
}

public Response postJson(String url, String json, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.headers(headers)
.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
return mOkHttpClient.newCall(request).execute();
}

public <T> Response put(String url, T t, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.put(RequestBody.create(JSON, "")).url(url).headers(headers);
if (t != null) {
RequestBody body = RequestBody.create(JSON, JsonUtils.toJSONString(t));
requestBuilder.put(body);
}
Request request = requestBuilder.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
Call call = mOkHttpClient.newCall(request);
return call.execute();
}

public Response putJson(String url, String json, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.put(body)
.headers(headers)
.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
return mOkHttpClient.newCall(request).execute();
}

public <T> Response delete(String url, T t, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
Request.Builder requestBuilder = new Request.Builder();
requestBuilder.delete().url(url).headers(headers);
if (t != null) {
RequestBody body = RequestBody.create(JSON, JsonUtils.toJSONString(t));
requestBuilder.delete(body);
}
Request request = requestBuilder.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
Call call = mOkHttpClient.newCall(request);
return call.execute();
}

public Response deleteJson(String url, String json, Headers headers) throws Exception {
if (headers == null) {
headers = new Headers.Builder().build();
}
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.delete(body)
.headers(headers)
.build();
logger.info("okhttp url : [{}] {} \nheader : {} \nrequestBody : {}", request.method(), request.url(), request.headers(), getRequestBody(request));
return mOkHttpClient.newCall(request).execute();
}

private static String getRequestBody(Request request) throws IOException {
Buffer buffer = new Buffer();
if (request.body() != null) {
request.body().writeTo(buffer);
return buffer.clone().readUtf8();
}
return "";
}

}

OkhttpUtils 工具类
https://cason.work/2022/07/26/OkhttpUtils 工具类/
作者
Cason Mo
发布于
2022年7月26日
许可协议