import com.andata.xintong.pojo.resp.KeplerDownloadRespDTO;
import okhttp3.*;
import okhttp3.Request.Builder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class OKHttpUtil {
private static final Logger log = LoggerFactory.getLogger(OKHttpUtil.class);
private static final MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
private static OkHttpClient httpClient = new OkHttpClient().newBuilder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
})
.build();
public static Object json(String url, Object content,Map<String,String> headers) {
log.info("json url:{} headers{}",url,headers);
Builder builder = new Builder().url(url);
if(headers != null && headers.size() > 0){
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(),entry.getValue());
}
}
String reqParams= getReqString(content);
log.info("okhttp json body {}", reqParams);
RequestBody requestBody = RequestBody.create(JSON_TYPE, reqParams);
builder.post(requestBody);
return execute(builder);
}
public static Object get(String url,Map<String,String> headers) {
log.info("get url:{} headers{}",url,headers);
Builder builder = new Builder().url(url);
if(headers != null && headers.size() > 0){
for (Map.Entry<String, String> entry : headers.entrySet()) {
builder.addHeader(entry.getKey(),entry.getValue());
}
}
return execute(builder);
}
/**
* 上传单个文件
*/
public static Object upload(String url, Map<String, String> headers, Map<String, Object> params) {
log.info("upload url:{} headers{}",url,headers);
Builder builder = new Builder().url(url);
MultipartBody.Builder multiBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
if(headers != null && headers.size() > 0){
for (Map.Entry<String, String> entry : headers.entrySet()) {
String haderKey = entry.getKey();
log.info("upload haderKey:{},val:{}",haderKey,entry.getValue());
multiBuilder.addFormDataPart(haderKey, entry.getValue());
}
}
if(params != null && params.size() > 0){
for (Map.Entry<String, Object> entry : params.entrySet()) {
Object value = entry.getValue();
if(value instanceof byte[]){
byte[] bytes = (byte[]) value;
String key = entry.getKey();
log.info("--->upload file param filename:{},bytes.length:{}",key,bytes.length);
multiBuilder.addFormDataPart(
key,
key,
RequestBody.create(MultipartBody.FORM, bytes)
);
}else {
String key = entry.getKey();
log.info("--->upload param key:{},val:{}",key,value);
multiBuilder.addFormDataPart(key, value.toString());
}
}
}
MultipartBody body = multiBuilder.build();
builder.post(body);
return execute(builder);
}
private static Object execute(Builder builder) {
long startTime = System.currentTimeMillis();
Request request = builder.build();
Call call = httpClient.newCall(request);
try (Response response = call.execute()) {
Headers headers = response.headers();
String disposition = headers.get("Content-disposition");
Object result = null;
if(disposition == null){
result = response.body().string();
}else {
KeplerDownloadRespDTO downloadRespDTO = new KeplerDownloadRespDTO();
downloadRespDTO.setBytes(response.body().bytes());
downloadRespDTO.setContentDisposition(disposition);
result = downloadRespDTO;
}
log.info("--cost:{} ms,body:{}",System.currentTimeMillis() - startTime,result);
return result;
} catch (IOException e) {
log.error("okhttp happen error", e);
throw new RuntimeException(e);
}
}
private static String getReqString(Object content) {
String reqParams=null;
if(content instanceof String){
reqParams = content.toString();
}else{
reqParams = JsonUtil.toJsonString(content);
}
return reqParams;
}
}