okhttputils java_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 headerMap, String json) {

if (DEBUG) {

LogUtil.d(TAG + "uploadJsonSync() 11 url:" + url

+ "\n 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 headerMap, String filePath) {

LogUtil.d(TAG + "uploadLogFileSync() url:" + url + "\n 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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值