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;
}

}

相关推荐
沈询-阿里34 分钟前
java-智能识别车牌号_基于spring ai和开源国产大模型_qwen vl
java·开发语言
AaVictory.40 分钟前
Android 开发 Java中 list实现 按照时间格式 yyyy-MM-dd HH:mm 顺序
android·java·list
LuckyLay1 小时前
Spring学习笔记_27——@EnableLoadTimeWeaving
java·spring boot·spring
向阳12181 小时前
Dubbo负载均衡
java·运维·负载均衡·dubbo
Gu Gu Study1 小时前
【用Java学习数据结构系列】泛型上界与通配符上界
java·开发语言
WaaTong2 小时前
《重学Java设计模式》之 原型模式
java·设计模式·原型模式
m0_743048442 小时前
初识Java EE和Spring Boot
java·java-ee
AskHarries2 小时前
Java字节码增强库ByteBuddy
java·后端
小灰灰__2 小时前
IDEA加载通义灵码插件及使用指南
java·ide·intellij-idea
夜雨翦春韭2 小时前
Java中的动态代理
java·开发语言·aop·动态代理