OkHttpUtils


import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
* date: 05/15/2020.
* author: lilei.
*/
public class OkHttpUtils {
private static final String TAG = AppConstants.APP_TAG + "OkHttpUtils ";
private static final boolean DEBUG = false;
private OkHttpClient mHttpsClient;
private static OkHttpUtils mInstance;

private OkHttpUtils() {
mHttpsClient = getUnsafeOkHttpClient();
}

/**
* getInstance.
*
* @return OkHttpUtils.
*/
public static OkHttpUtils getInstance() {
if (mInstance == null) {
mInstance = new OkHttpUtils();
}
return mInstance;
}

/**
* uploadJsonSync.
* This function should be call in thread.
*
* @param url url.
* @param headerMap Headers map.
* @param json body json.
* @return http response json.
*/
public synchronized String uploadJsonSync(
final String url, final Map<String, String> headerMap, String json) {
if (DEBUG) {
LogUtil.d(TAG + "uploadJsonSync() 11 url:" + url
+ " headerMap:" + headerMap + " json:" + json);
}
Headers.Builder builder = new Headers.Builder()
.add("char-set", "utf-8")
.add(AppConstants.HEADER_KEY_EVENT_ID, UUID.randomUUID().toString())
.add("Content-Type", "application/json");
if (null != headerMap) {
for (String key : headerMap.keySet()) {
String value = String.valueOf(headerMap.get(key));
builder.add(key, value);
}
}
Headers headers = builder.build();
if (DEBUG) {
LogUtil.d(TAG + "uploadJsonSync() 22 headers:" + headers);
}
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(mediaType, json);

Request request = new Request.Builder()
.headers(headers)
.url(url)
.post(body)
.build();
Response response = null;
try {
response = mHttpsClient.newCall(request).execute();
//response.body().string() This code can only be used
// once in the method body (including the use of printout)
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

/**
* uploadLogFileSync.
* This function should be call in thread.
*
* @param url url.
* @param headerMap Headers map.
* @param filePath Full file path.
* @return http response json.
*/
public synchronized String uploadLogFileSync(
final String url, final Map<String, String> headerMap, String filePath) {
LogUtil.d(TAG + "uploadLogFileSync() url:" + url + " headerMap:" + headerMap);
File file = new File(filePath);
if (!file.exists()) {
LogUtil.d(TAG + "uploadLogFileSync() cannot find file:" + file);
return null;
}
Headers.Builder builder = new Headers.Builder()
.add("char-set", "utf-8")
.add("Content-Type", "multipart/form-data");
if (null != headerMap) {
for (String key : headerMap.keySet()) {
String value = headerMap.get(key);
builder.add(key, value);
}
}
Headers headers = builder.build();
LogUtil.d(TAG + "uploadLogFileSync() 22 headers:" + headers);

MediaType mediaType = MediaType.parse("multipart/form-data");
//file is the file to be uploaded,
// and mediaType is the request body type declared in the previous step.
RequestBody requestBody = RequestBody.create(mediaType, file);
//Create the request body of the file form, put the file request
//body and text parameters into the form.
MultipartBody multipartBody = new MultipartBody.Builder()
.addFormDataPart("file", file.getName(), requestBody)
.build();

Request request = new Request.Builder()
.headers(headers)
.url(url)
.post(multipartBody)
.build();
Response response = null;
try {
response = mHttpsClient.newCall(request).execute();
//response.body().string() This code can only be used
//once in the method body (including the use of printout)
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}

return null;
}

private static OkHttpClient getUnsafeOkHttpClient() {
try {
final TrustManager[] trustAllCerts = 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[] {};
}
}
};

final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
final javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(3, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});

OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
原文地址:https://www.cnblogs.com/adamli/p/13139653.html