OkHttp3封装第一版
导入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
代码如下
package com.xxxxxxxx
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.OkHttpClient.Builder;
import org.apache.commons.lang3.StringUtils;
public class OKHttpConfiguration {
private static OkHttpClient okHttpClient;
private static DateFormat datetimeFormat;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static final String DefaultCertification = " Bearer ";
private static final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}};
private static final SSLContext trustAllSslContext;
private static final SSLSocketFactory trustAllSslSocketFactory;
public OKHttpConfiguration() {
}
public static OkHttpClient getOkHttpClient() {
if (Objects.nonNull(okHttpClient)) {
return okHttpClient;
} else {
okHttpClient = (new Builder()).sslSocketFactory(trustAllSslSocketFactory, (X509TrustManager)trustAllCerts[0]).hostnameVerifier((hostname, session) -> {
return true;
}).connectTimeout(Long.parseLong((String)Optional.ofNullable(NIFIClientYmlConfiguration.applicationMap.get("nifi.client.connectionTimeOut")).orElse("10")), TimeUnit.SECONDS).readTimeout(Long.parseLong((String)Optional.ofNullable(NIFIClientYmlConfiguration.applicationMap.get("nifi.client.readTimeOut")).orElse("10")), TimeUnit.SECONDS).writeTimeout(Long.parseLong((String)Optional.ofNullable(NIFIClientYmlConfiguration.applicationMap.get("nifi.client.writeTimeOut")).orElse("10")), TimeUnit.SECONDS).build();
return okHttpClient;
}
}
public static Call buildGetCall(String prefixPath, List<Pair> queryParams, Map<String, String> headerParams) {
String url = buildUrl(prefixPath, queryParams);
okhttp3.Request.Builder reqBuilder = (new okhttp3.Request.Builder()).url(url);
processHeaderParams(headerParams, reqBuilder);
Request request = reqBuilder.build();
return getOkHttpClient().newCall(request);
}
public static Call buildPostCall(String url, Map<String, String> headerParams, RequestBody requestBody) {
okhttp3.Request.Builder reqBuilder = (new okhttp3.Request.Builder()).url(url);
processHeaderParams(headerParams, reqBuilder);
Request request = reqBuilder.post(requestBody).build();
return getOkHttpClient().newCall(request);
}
public static Call buildPutCall(String url, Map<String, String> headerParams, RequestBody requestBody) {
okhttp3.Request.Builder reqBuilder = (new okhttp3.Request.Builder()).url(url);
processHeaderParams(headerParams, reqBuilder);
Request request = reqBuilder.put(requestBody).build();
return getOkHttpClient().newCall(request);
}
public static Call buildDeleteCall(String prefixPath, List<Pair> queryParams, Map<String, String> headerParams, RequestBody requestBody) {
String url = buildUrl(prefixPath, queryParams);
okhttp3.Request.Builder reqBuilder = (new okhttp3.Request.Builder()).url(url);
processHeaderParams(headerParams, reqBuilder);
Request request = reqBuilder.delete(requestBody).build();
return getOkHttpClient().newCall(request);
}
private static void processHeaderParams(Map<String, String> headerParams, okhttp3.Request.Builder reqBuilder) {
Iterator var2 = headerParams.entrySet().iterator();
while(var2.hasNext()) {
Entry<String, String> param = (Entry)var2.next();
reqBuilder.header((String)param.getKey(), parameterToString(param.getValue()));
}
}
private static String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDatetime((Date)param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
Object o;
for(Iterator var2 = ((Collection)param).iterator(); var2.hasNext(); b.append(String.valueOf(o))) {
o = var2.next();
if (b.length() > 0) {
b.append(",");
}
}
return b.toString();
} else {
return String.valueOf(param);
}
}
private static String formatDatetime(Date date) {
return datetimeFormat.format(date);
}
public static String buildUrl(String prefixPath, List<Pair> queryParams) {
StringBuilder url = new StringBuilder();
url.append(prefixPath);
if (queryParams != null && !queryParams.isEmpty()) {
String prefix = prefixPath.contains("?") ? "&" : "?";
Iterator var4 = queryParams.iterator();
while(var4.hasNext()) {
Pair param = (Pair)var4.next();
if (!StringUtils.isBlank(param.getValue())) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = parameterToString(param.getValue());
url.append(escapeString(param.getName())).append("=").append(escapeString(value));
}
}
}
return url.toString();
}
private static String escapeString(String str) {
try {
return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException var2) {
return str;
}
}
public static List<Pair> convertToQueryParams(Object o) {
if (Objects.isNull(o)) {
return Collections.emptyList();
} else {
List<Pair> queryParams = new ArrayList();
Field[] field = o.getClass().getDeclaredFields();
Field[] var3 = field;
int var4 = field.length;
for(int var5 = 0; var5 < var4; ++var5) {
Field aField = var3[var5];
String valueName = aField.getName();
String name = aField.getName().substring(0, 1).toUpperCase() + aField.getName().substring(1);
Method m = null;
String value = null;
try {
m = o.getClass().getMethod("get" + name);
Object obj = m.invoke(o);
value = Objects.nonNull(obj) ? obj.toString() : null;
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException var12) {
return Collections.emptyList();
}
if (!StringUtils.isBlank(value)) {
queryParams.add(new Pair(valueName, value));
}
}
return queryParams;
}
}
public static List<Pair> convertToQueryParams(Object o, DateTimeFormatter dateTimeFormatter) {
if (Objects.isNull(o)) {
return Collections.emptyList();
} else {
List<Pair> queryParams = new ArrayList();
Field[] field = o.getClass().getDeclaredFields();
Field[] var4 = field;
int var5 = field.length;
for(int var6 = 0; var6 < var5; ++var6) {
Field aField = var4[var6];
String valueName = aField.getName();
String name = aField.getName().substring(0, 1).toUpperCase() + aField.getName().substring(1);
Method m = null;
String value = null;
try {
m = o.getClass().getMethod("get" + name);
Object obj = m.invoke(o);
if (obj instanceof LocalDateTime) {
value = dateTimeFormatter.format((LocalDateTime)obj);
} else {
value = Objects.nonNull(obj) ? obj.toString() : null;
}
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException var13) {
return Collections.emptyList();
}
if (!StringUtils.isBlank(value)) {
queryParams.add(new Pair(valueName, value));
}
}
return queryParams;
}
}
static {
try {
trustAllSslContext = SSLContext.getInstance("SSL");
trustAllSslContext.init((KeyManager[])null, trustAllCerts, new SecureRandom());
} catch (KeyManagementException | NoSuchAlgorithmException var1) {
throw new RuntimeException(var1);
}
trustAllSslSocketFactory = trustAllSslContext.getSocketFactory();
}
}
@Data
public class Pair {
private String name;
private String value;
}
OkHttp3封装第二版链接: OkHttp3封装第二版.
2021-12-23:又发现了Forest框架,更简单的封装
Forest Http使用分享: https://blog.csdn.net/weixin_43916074/article/details/122078318.