1. 依赖
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.14.4</version>
</dependency>
2. 工具类
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Slf4j
public class OkHttpUtil {
private static final MediaType JSON =
MediaType.get(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);
private static final MediaType XML =
MediaType.get(org.springframework.http.MediaType.APPLICATION_XML_VALUE);
public static void main(String[] args) {
String s = OkHttpUtil.get("https://www.baidu.com/");
System.out.println(s);
}
public enum TimeOutKey{
CONNECT("connect")
, READ("read")
, WRITE("write");
private String val;
TimeOutKey(String val){
this.val = val;
}
}
private static final int CONNECT_TIMEOUT = 30;
private static final int READ_TIMEOUT = 30;
private static final int WRITE_TIMEOUT = 30;
private static ConnectionPool pool = new ConnectionPool(200, 5, TimeUnit.MINUTES);
private static OkHttpClient getHttp(Integer connect, Integer read, Integer write) {
OkHttpClient okHttpClient =
new OkHttpClient.Builder()
.retryOnConnectionFailure(false)
.connectionPool(pool)
.connectTimeout(null == connect ? CONNECT_TIMEOUT : connect, TimeUnit.SECONDS)
.readTimeout(null == read ? READ_TIMEOUT : read, TimeUnit.SECONDS)
.writeTimeout(null == write ? WRITE_TIMEOUT : write, TimeUnit.SECONDS)
.sslSocketFactory(createSSLSocketFactory())
.hostnameVerifier(new TrustAllHostnameVerifier())
.build();
return okHttpClient;
}
private static SSLSocketFactory createSSLSocketFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
log.error("Exception", e);
}
return ssfFactory;
}
private static class TrustAllCerts implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
private static class TrustAllHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
public static String doPost(String url, Map<String, String> maps, Map<String, Integer> timeOutMap) {
FormBody.Builder formBodyBuilder = new FormBody.Builder();
Set<Map.Entry<String, String>> entrySet = maps.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
formBodyBuilder.add(entry.getKey(), String.valueOf(entry.getValue()));
}
RequestBody body = formBodyBuilder.build();
Request request = new Request.Builder().url(url).post(body).build();
return execute(request, timeOutMap);
}
public static String doPost(String url) {
return doPost(url, null, null);
}
public static String doPostJson(String url, String json, Map<String, Integer> timeOutMap) {
Request request =
new Request.Builder()
.url(url)
.addHeader("Connection", "close")
.post(RequestBody.create(JSON, json))
.build();
return execute(request, timeOutMap);
}
public static String get(String url, Map<String, String> queries, Map<String, Integer> timeOutMap) {
StringBuffer sb = new StringBuffer(url);
if (queries != null && queries.keySet().size() > 0) {
boolean firstFlag = true;
Iterator iterator = queries.entrySet().iterator();
while(iterator.hasNext()) {
Map.Entry entry = (Map.Entry<String, String>) iterator.next();
if (firstFlag) {
sb.append("?" + entry.getKey() + "=" + entry.getValue());
firstFlag = false;
} else {
sb.append("&" + entry.getKey() + "=" + entry.getValue());
}
}
}
Request request =
new Request.Builder().url(sb.toString()).addHeader("Connection", "close").build();
return execute(request, timeOutMap);
}
public static String get(String url) {
return get(url, null, null);
}
public static String postXml(String url, String xml, Map<String, Integer> timeOutMap) {
RequestBody requestBody = RequestBody.create(XML, xml);
Request request =
new Request.Builder().url(url).post(requestBody).addHeader("Connection", "close").build();
return execute(request, timeOutMap);
}
public static String postJson(String url, String json, Map<String, Integer> timeOutMap) {
RequestBody body = RequestBody.create(JSON, json);
Request request =
new Request.Builder().url(url).addHeader("Connection", "close").post(body).build();
return execute(request, timeOutMap);
}
public static String put(String url, Map<String, Integer> timeOutMap) {
Request request = new Request.Builder().url(url).addHeader("Connection", "close").build();
return execute(request, timeOutMap);
}
public static String putJson(String url, String json, Map<String, Integer> timeOutMap) {
RequestBody body = RequestBody.create(JSON, json);
Request request =
new Request.Builder().url(url).addHeader("Connection", "close").put(body).build();
return execute(request, timeOutMap);
}
private static String execute(Request request, Map<String, Integer> timeOutMap) {
Response response = null;
try {
if (null == timeOutMap){
response = getHttp(null, null, null).newCall(request).execute();
}else{
response = getHttp(timeOutMap.get(TimeOutKey.CONNECT.val), timeOutMap.get(TimeOutKey.READ.val), timeOutMap.get(TimeOutKey.WRITE.val)).newCall(request).execute();
}
if (response.isSuccessful()) {
return response.body().string();
}
} catch (Exception e) {
log.error("Exception", e);
} finally {
if (response != null) {
response.close();
}
}
return null;
}
}