https请求无ssl证书的工具类

发布时间:2024年01月19日

运行环境:java8+springboot

package com.test.appstore.common.utils;

import com.alibaba.fastjson2.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: okhttp 请求工具类
 */
@Component
@Slf4j
public class HttpClientUtil {

    private OkHttpClient client = null;

    private OkHttpClient unsafeOkHttpClient = null;

    private static final String UNEXPECTED_CODE_TEXT = "unexpected code ";

    @Value("${data.center.name}")
    private String dataCenterName;

    @PostConstruct
    public void init() {
        client = getsafeOkHttpClient();
        log.info("init OkHttpClient");

        unsafeOkHttpClient = getUnsafeOkHttpClient();
        log.info("init unsafeOkHttpClient");
    }

    private OkHttpClient getsafeOkHttpClient() {
        return new OkHttpClient.Builder()
                .connectionSpecs(Collections.singletonList(ConnectionSpec.COMPATIBLE_TLS))
                .connectTimeout(2, TimeUnit.SECONDS)
                .writeTimeout(2, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS)
                .build();
    }

    @SneakyThrows
    private OkHttpClient getUnsafeOkHttpClient() {
        final TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) {
                    }

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

        // 创建一个不验证证书的 SSLContext,并使用上面的TrustManager初始化
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

        // 使用上面创建的SSLContext创建一个SSLSocketFactory
        javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        return new OkHttpClient.Builder()
                .connectionSpecs(Collections.singletonList(ConnectionSpec.COMPATIBLE_TLS))
                .connectTimeout(2, TimeUnit.SECONDS)
                .writeTimeout(2, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS)
                .sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
                .hostnameVerifier((s, sslSession) -> true)
                .build();
    }

    @SneakyThrows
    private OkHttpClient selectOkHttpClient(String urlStr) {
        if (dataCenterName.equalsIgnoreCase("DEV") || dataCenterName.startsWith("TEST-")) {
            URL url = new URL(urlStr);
            String hostName = url.getHost();
            if (hostName.matches("[0-9\\.]+")) {
                return unsafeOkHttpClient;
            } else {
                return client;
            }
        }

        return client;
    }

    @SneakyThrows
    public String get(String url, Map<String, String> headMap, Map<String, Object> bodyParams) {
        url = UrlUtil.appendParamsUrl(url, bodyParams);
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headMap)) {
            Headers headers = Headers.of(headMap);
            requestBuilder.headers(headers);
        }
        log.info("get request: url={}, heads={}", url, headMap);

        Request request = requestBuilder.build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException(UNEXPECTED_CODE_TEXT + response);
        }

        if (response.body() == null) {
            log.warn("get response body is null");
            return null;
        }

        return response.body().string();
    }

    /**
     * request by application/json
     *
     * @param url
     * @param headMap
     * @param bodyParams
     * @return
     */
    @SneakyThrows
    public String postJson(String url, Map<String, String> headMap, Map<String, Object> bodyParams) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headMap)) {
            Headers headers = Headers.of(headMap);
            requestBuilder.headers(headers);
        }

        log.info("postJson request: url={}, heads={}, bodyParams={}", url, headMap, bodyParams);

        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(bodyParams));
        Request request = requestBuilder.post(body).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException(UNEXPECTED_CODE_TEXT + response);
        }

        if (response.body() == null) {
            log.warn("postJson response body is null");
            return null;
        }

        return response.body().string();

    }

    @SneakyThrows
    public String postXml(String url, Map<String, String> headMap, String bodyParams) {
        MediaType mediaType = MediaType.parse("text/xml;charset=UTF-8");
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headMap)) {
            Headers headers = Headers.of(headMap);
            requestBuilder.headers(headers);
        }

        log.info("postJson request: url={}, heads={}, bodyParams={}", url, headMap, bodyParams);

        RequestBody body = RequestBody.create(mediaType, bodyParams);
        Request request = requestBuilder.post(body).build();
        Response response = this.selectOkHttpClient(url).newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException(UNEXPECTED_CODE_TEXT + response);
        }

        if (response.body() == null) {
            log.warn("postJson response body is null");
            return null;
        }

        return response.body().string();
    }

    /**
     * request by application/x-www-form-urlencode
     *
     * @param url
     * @param headMap
     * @param bodyParams
     * @return
     */
    @SneakyThrows
    public String post(String url, Map<String, String> headMap, Map<String, Object> bodyParams) {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headMap)) {
            Headers headers = Headers.of(headMap);
            requestBuilder.headers(headers);
        }

        if (CollectionUtils.isEmpty(bodyParams)) {
            throw new IOException("bodyParams is empty");
        }
        log.info("post request: url={}, heads={}, bodyParams={}", url, headMap, bodyParams);

        FormBody.Builder builder = new FormBody.Builder();
        bodyParams.keySet().forEach(key -> builder.add(key, bodyParams.get(key) != null && bodyParams.get(key).getClass() == String.class ? (String) bodyParams.get(key) : JSON.toJSONString(bodyParams.get(key))));
        RequestBody body = builder.addEncoded("charset", "utf-8").build();
        Request request = requestBuilder.post(body).build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException(UNEXPECTED_CODE_TEXT + response);
        }

        if (response.body() == null) {
            log.warn("post response body is null");
            return null;
        }

        return response.body().string();
    }

    @SneakyThrows
    public byte[] download(String url, Map<String, String> headMap, Map<String, Object> bodyParams) {
        url = UrlUtil.appendParamsUrl(url, bodyParams);
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (!CollectionUtils.isEmpty(headMap)) {
            Headers headers = Headers.of(headMap);
            requestBuilder.headers(headers);
        }
        log.info("download request: url={}, heads={}", url, headMap);

        Request request = requestBuilder.build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException(UNEXPECTED_CODE_TEXT + response);
        }

        if (response.body() == null) {
            log.warn("download response body is null");
            return null;
        }
        return response.body().bytes();
    }


}
文章来源:https://blog.csdn.net/lj1404536198/article/details/135693905
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。