org.zodiac.okhttp.util.OkHttpUtil Maven / Gradle / Ivy
The newest version!
package org.zodiac.okhttp.util;
import java.io.File;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Map;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zodiac.okhttp.Exchange;
import org.zodiac.okhttp.FormBuilder;
import org.zodiac.okhttp.HttpRequest;
import org.zodiac.sdk.toolkit.http.HttpResponseStatusEnum;
import org.zodiac.sdk.toolkit.util.collection.CollUtil;
import org.zodiac.sdk.toolkit.util.lang.StrUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* Http请求工具类。
*
*/
public class OkHttpUtil {
protected OkHttpUtil() {
super();
}
private static Logger log = LoggerFactory.getLogger(OkHttpUtil.class);
/****
* HTTP方式下载文件。
*
* @param fileUrl 文件的 URL
* @param targetFilePath 目标文件存放路径
* @return 是否成功
*/
public static boolean downloadHttpFile(String fileUrl, String targetFilePath) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(fileUrl)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
if (response.isSuccessful()){
FileUtils.copyInputStreamToFile(response.body().byteStream(), new File(targetFilePath));
}
}
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
});
return true;
}
/**
* GET 请求。
*
* @param url 请求的url
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return String
*/
public static String get(String url, Map queries) {
return get(url, null, queries);
}
/**
* GET 请求。
*
* @param url 请求的url
* @param headers 请求头
* @param queries 请求的参数,在浏览器?后面的数据,没有可以传null
* @return String
*/
public static String get(String url, Map headers, Map queries) {
/*添加请求头。*/
HttpRequest httpRequest = HttpRequest.get(url);
if (headers != null && headers.keySet().size() > 0) {
headers.forEach(httpRequest::addHeader);
}
/*添加参数。*/
httpRequest.queryMap(queries);
return httpRequest.execute().asString();
}
/**
* POST 请求。
*
* @param url 请求的url
* @param params post form 提交的参数
* @return String
*/
public static String post(String url, Map params) {
return exchange(url, null, params).asString();
}
/**
* POST 请求。
*
* @param url 请求的url
* @param headers 请求头
* @param params post form 提交的参数
* @return String
*/
public static String post(String url, Map headers, Map params) {
return exchange(url, headers, params).asString();
}
/**
* POST请求发送JSON数据。
*
* @param url 请求的url
* @param json 请求的json串
* @return String
*/
public static String postJson(String url, String json) {
return exchange(url, null, json).asString();
}
/**
* POST 请求发送JSON数据。
*
* @param url 请求的url
* @param headers 请求头
* @param json 请求的json串
* @return String
*/
public static String postJson(String url, Map headers, String json) {
return exchange(url, headers, json).asString();
}
/**
* POST 请求发送表单数据。
*
* @param url 请求的url
* @param headers 请求头
* @param formBody 请求的表单数据
* @return String
*/
public static String postFormOfString(String url, Map headers, Map formBody) {
Response response = postFormOfResponse(url, headers, formBody);
if (null == response) {
return null;
}
try {
return response.body().string();
} catch (IOException e) {
log.warn("请求调用解析异常 : " + url, e);
return null;
}
}
/**
* POST 请求发送表单数据。
*
* @param url 请求的url
* @param headers 请求头
* @param formBody 请求的表单数据
* @return String
*/
public static Response postFormOfResponse(String url, Map headers, Map formBody) {
OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();
if(StrUtil.startsWithIgnoreCase(url, "https://")) {
withHttps(clientBuilder);
}
FormBody.Builder bodyBuilder = new FormBody.Builder();
if(CollUtil.isNotEmptyMap(formBody)) {
for(Map.Entry entry : formBody.entrySet()) {
bodyBuilder.add(entry.getKey(), entry.getValue());
}
}
Request request = new Request.Builder().url(url)
.post(bodyBuilder.build())
.build();
Call call = clientBuilder.build().newCall(request);
try {
Response response = call.execute();
/*判断状态码。*/
if(response.code() >= HttpResponseStatusEnum.BAD_REQUEST.value()) {
log.warn("请求调用异常 : " + url);
return null;
}
return response;
} catch (IOException e) {
log.warn("请求调用解析异常 : " + url, e);
return null;
}
}
public static Exchange exchange(String url, Map headers, Map params) {
HttpRequest httpRequest = HttpRequest.post(url);
/*添加请求头。*/
if (headers != null && headers.keySet().size() > 0) {
headers.forEach(httpRequest::addHeader);
}
FormBuilder formBuilder = httpRequest.formBuilder();
/*添加参数。*/
if (params != null && params.keySet().size() > 0) {
params.forEach(formBuilder::add);
}
return formBuilder.execute();
}
public static Exchange exchange(String url, Map headers, String content) {
HttpRequest httpRequest = HttpRequest.post(url);
/*添加请求头。*/
if (headers != null && headers.keySet().size() > 0) {
headers.forEach(httpRequest::addHeader);
}
return httpRequest.bodyString(content).execute();
}
public static String exchangeString(String url, Map headers, String content) {
Exchange exchange = exchange(url, headers, content);
if (null == exchange) {
return null;
}
try {
return exchange.asString();
} catch (Exception e) {
log.warn("请求调用解析异常 : " + url, e);
return null;
}
}
public static String executeCall(Call call, String url) {
try {
Response response = call.execute();
/*判断状态码。*/
if(response.code() >= HttpResponseStatusEnum.BAD_REQUEST.value()) {
log.warn("请求调用异常 : " + url);
return null;
}
return response.body().string();
} catch (IOException e) {
log.warn("请求调用解析异常 : " + url, e);
return null;
}
}
/**
* 开启 HTTPS
。
*
* @param builder 客户端构建器
*/
public static void withHttps(OkHttpClient.Builder builder) {
try {
TrustManager[] trustManagers = buildTrustManagers();
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, new SecureRandom());
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0]);
builder.hostnameVerifier((hostname, session) -> true);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
log.warn("构建https请求异常", e);
}
}
private static TrustManager[] buildTrustManagers() {
return new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};
}
}