OkHttpUtils工具类,复制粘贴即可使用

import com.pflm.mall.ext.service.config.SkipSSLSocketClient;

import okhttp3.*;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.Map;

import java.util.concurrent.TimeUnit;

public class OkHttpUtils {

static ConnectionPool pool = new ConnectionPool(200, 5, TimeUnit.MINUTES);

private static final OkHttpClient client =
        new OkHttpClient.Builder()
                .connectionPool(pool)
                // 设置连接超时时间
                .connectTimeout(60, TimeUnit.SECONDS)
                // 从连接成功到响应的总时间
                .readTimeout(120, TimeUnit.SECONDS)
                // 写入超时时间
                .writeTimeout(120, TimeUnit.SECONDS)
                // 忽略ssl
                .sslSocketFactory(SkipSSLSocketClient.getSSLSocketFactory(), SkipSSLSocketClient.X509)
                .hostnameVerifier(SkipSSLSocketClient.getHostnameVerifier())
                .retryOnConnectionFailure(true)
                .build();


public static final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");


/**
 * 发起Get请求
 *
 * @param url    url
 * @param params 参数
 * @return 响应结果
 */
public static String doGet(String url, Map<String, Object> params) {
    Call call = createGetCall(url, params);
    return execute(call);
}

/**
 * 发起Get请求,返回请求流,用于文件下载
 *
 * @param url    url
 * @param params 参数
 * @return 响应结果
 */
public static InputStream doGetFileStream(String url, Map<String, Object> params) {
    Call call = createGetCall(url, params);
    return executeAndReturnStream(call);
}

/**
 * 发起 Post请求, 使用form表单参数
 *
 * @param url    url
 * @param params 参数
 * @return 响应结果
 */
public static String doPost(String url, Map<String, Object> params) {
    Call call = createPostCall(url, params);
    return execute(call);
}

/**
 * 发起 post请求, 使用json参数
 *
 * @param url  url
 * @param json json参数
 * @return resp
 */
public static String doPost(String url, String json) {
    Call call = createPostJsonCall(url, json);
    return execute(call);
}


/**
 * [异步] 发起Get请求
 *
 * @param url      url
 * @param params   参数
 * @param callback 回调方法
 */
public static void doGetAsync(String url, Map<String, Object> params, Callback callback) {
    Call call = createGetCall(url, params);
    call.enqueue(callback);
}

/**
 * [异步] 发起 Post请求
 *
 * @param url    url
 * @param params 参数
 */
public static void doPostAsync(String url, Map<String, Object> params, Callback callback) {
    Call call = createPostCall(url, params);
    call.enqueue(callback);
}

/**
 * [异步] 发起 post请求, 使用json参数
 *
 * @param url  url
 * @param json json参数
 */
public static void doPostAsync(String url, String json, Callback callback) {
    Call call = createPostJsonCall(url, json);
    call.enqueue(callback);
}


/**
 * Get请求, 构造 Call对象
 *
 * @param url    请求url
 * @param params 请求参数
 * @return Call
 */
private static Call createGetCall(String url, Map<String, Object> params) {

    Request.Builder builder = new Request.Builder();
    Request request = builder.url(url).build();
    // 设置参数
    HttpUrl httpUrl = createHttpUrl(request, params);
    builder.url(httpUrl).build();

    return client.newCall(builder.build());
}

/**
 * Post请求, 构造 Call对象
 *
 * @param url    请求url
 * @param params 请求参数
 * @return Call
 */
private static Call createPostCall(String url, Map<String, Object> params) {
    Request request = new Request.Builder()
            .post(createFormBody(params))
            .url(url)
            .build();
    return client.newCall(request);
}

/**
 * Post请求, 构造 Call对象
 *
 * @param url  请求url
 * @param json 请求参数
 * @return Call
 */
private static Call createPostJsonCall(String url, String json) {
    Request request = new Request.Builder()
            .post(RequestBody.create(MEDIA_TYPE_JSON, json))
            .url(url)
            .build();
    return client.newCall(request);
}


/**
 * 为 get请求设置参数
 *
 * @param request request对象
 * @param params 请求参数
 * @return 设置了参数的 HttpUrl对象
 */
private static HttpUrl createHttpUrl(Request request, Map<String, Object> params) {
    HttpUrl.Builder urlBuilder = request.url().newBuilder();
    if (params != null && params.size() > 0) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            urlBuilder.addQueryParameter(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    return urlBuilder.build();
}


/**
 * 为 post请求设置参数
 *
 * @param params 请求参数
 * @return FormBody
 */
private static FormBody createFormBody(Map<String, Object> params) {
    FormBody.Builder builder = new FormBody.Builder();
    if (params != null && params.size() > 0) {
        for (Map.Entry<String, Object> entry : params.entrySet()) {
            builder.add(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    return builder.build();
}


/**
 * 同步执行 http请求
 *
 * @param call call对象
 * @return 响应结果
 */
public static String execute(Call call) {
    String respStr = "";
    try {
        ResponseBody body = call.execute().body();
        if (body != null) {
            respStr = body.string();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return respStr;
}

/**
 * 同步执行 http请求
 *
 * @param call call对象
 * @return 响应结果
 */
public static InputStream executeAndReturnStream(Call call) {
    InputStream respStr =  null;
    try {
        ResponseBody body = call.execute().body();
        if (body != null) {
            return body.byteStream();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return respStr;
}


/**
 * 将inputstream转为Base64
 *
 * @param is
 * @return
 * @throws Exception
 */
public static String inputStreamToBase64(InputStream is) throws Exception {
    byte[] data = null;
    try {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = is.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        data = swapStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new Exception("输入流关闭异常");
            }
        }
    }

    return Base64.encodeBase64String(data);
}

}

import javax.net.ssl.*;

import java.net.Socket;

import java.security.SecureRandom;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

public class SkipSSLSocketClient {

/**
 * 获取TrustManager
 * 对于在Android 10及以上的设备上,会出现设备信任问题[用X509ExtendedTrustManager兼容]
 */
public static X509ExtendedTrustManager X509 = new X509ExtendedTrustManager() {
    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
        // TODO document why this method is empty
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {
        // TODO document why this method is empty
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
        // TODO document why this method is empty
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {
        // TODO document why this method is empty
    }

    @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        // TODO document why this method is empty
    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        // TODO document why this method is empty
    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return new X509Certificate[0];
    }
};

/**
 * 获取这个SSLSocketFactory
 */
public static SSLSocketFactory getSSLSocketFactory() {
    try {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{X509}, new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}


/**
 * 获取HostnameVerifier
 */
public static HostnameVerifier getHostnameVerifier() {
    return (s, sslSession) -> true;
}

}

相关推荐
李小白665 分钟前
Spring MVC(上)
java·spring·mvc
GoodStudyAndDayDayUp18 分钟前
IDEA能够从mapper跳转到xml的插件
xml·java·intellij-idea
装不满的克莱因瓶1 小时前
【Redis经典面试题六】Redis的持久化机制是怎样的?
java·数据库·redis·持久化·aof·rdb
n北斗1 小时前
常用类晨考day15
java
骇客野人1 小时前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言
yuanbenshidiaos2 小时前
c++---------数据类型
java·jvm·c++
向宇it2 小时前
【从零开始入门unity游戏开发之——C#篇25】C#面向对象动态多态——virtual、override 和 base 关键字、抽象类和抽象方法
java·开发语言·unity·c#·游戏引擎
Lojarro2 小时前
【Spring】Spring框架之-AOP
java·mysql·spring
莫名其妙小饼干2 小时前
网上球鞋竞拍系统|Java|SSM|VUE| 前后端分离
java·开发语言·maven·mssql
isolusion3 小时前
Springboot的创建方式
java·spring boot·后端