okHttp工具类

okHttp工具类

一、导入依赖

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.8.1</version>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.6.4</version>
        </dependency>

二、HttpClientConfig配置类

public class HttpClientConfig {

    private String masterUrl;
    private boolean trustCerts;
    private String username;
    private String password;
    private int connectionTimeout;
    private int requestTimeout;
    private int websocketPingInterval;
    private int maxConcurrentRequestsPerHost;

    private int maxConnection;

    private String httpProxy;
    private String httpsProxy;
    private String proxyUsername;
    private String proxyPassword;
    private String userAgent;
    private TlsVersion[] tlsVersions = new TlsVersion[]{TLS_1_2};
    private String[] noProxy;
    public static final String HTTP_PROTOCOL_PREFIX = "http://";
    public static final String HTTPS_PROTOCOL_PREFIX = "https://";
    
    //省略get、set方法
}

三、HttpClientUtils工具类

package com.yolo.springbootzkeco.util;

import cn.hutool.json.JSONUtil;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

import static okhttp3.ConnectionSpec.CLEARTEXT;

public class HttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    private static final Map<String, OkHttpClient> map_clients = new ConcurrentHashMap<>();
    private static OkHttpClient okHttpClient2;

    private HttpClientUtils() {
    }

    /**
     * 饿汉式单例
     */
    private static OkHttpClient getInstance(final HttpClientConfig config) {
        if (map_clients.containsKey(md5Key(config))) {
            return map_clients.get(md5Key(config));
        }
        OkHttpClient okHttpClient = createHttpClient(config);
        map_clients.put(md5Key(config), okHttpClient);
        return okHttpClient;
    }

    /**
     * 懒汉式单例
     */
    private static OkHttpClient getOkHttpClient(HttpClientConfig config) {
        if (okHttpClient2 == null) {
            okHttpClient2 = createHttpClient(config);
        }
        return okHttpClient2;
    }

    private static String md5Key(HttpClientConfig config) {
        return getMD5InHex( config.getMasterUrl() + "/" + config.getUsername() + "/" + config.getPassword() + "/");
    }

    private static String getMD5InHex(String data) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(data.getBytes());
            byte[] result = messageDigest.digest();
            return new BigInteger(1, result).toString(16);
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    private static OkHttpClient createHttpClient(final HttpClientConfig config) {
        try {
            OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();

            // Follow any redirects
            httpClientBuilder.followRedirects(true);
            httpClientBuilder.followSslRedirects(true);

            if (config.isTrustCerts()) {
                httpClientBuilder.hostnameVerifier((s, sslSession) -> true);
            }

            TrustManager[] trustManagers = buildTrustManagers();
            httpClientBuilder.sslSocketFactory(createSSLSocketFactory(trustManagers), (X509TrustManager) trustManagers[0]);

            if (config.getConnectionTimeout() > 0) {
                httpClientBuilder.connectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS);
            }

            if (config.getRequestTimeout() > 0) {
                httpClientBuilder.readTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS);
            }

            if (config.getWebsocketPingInterval() > 0) {
                httpClientBuilder.pingInterval(config.getWebsocketPingInterval(), TimeUnit.MILLISECONDS);
            }

            if (config.getMaxConcurrentRequestsPerHost() > 0) {
                Dispatcher dispatcher = new Dispatcher();
                dispatcher.setMaxRequestsPerHost(config.getMaxConcurrentRequestsPerHost());
                httpClientBuilder.dispatcher(dispatcher);
            }

            if (config.getMaxConnection() > 0) {
                ConnectionPool connectionPool = new ConnectionPool(config.getMaxConnection(), 60, TimeUnit.SECONDS);
                httpClientBuilder.connectionPool(connectionPool);
            }

            // Only check proxy if it's a full URL with protocol
            if (config.getMasterUrl().toLowerCase().startsWith(HttpClientConfig.HTTP_PROTOCOL_PREFIX) || config.getMasterUrl().startsWith(HttpClientConfig.HTTPS_PROTOCOL_PREFIX)) {
                try {
                    URL proxyUrl = getProxyUrl(config);
                    if (proxyUrl != null) {
                        httpClientBuilder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort())));

                        if (config.getProxyUsername() != null) {
                            httpClientBuilder.proxyAuthenticator((route, response) -> {

                                String credential = Credentials.basic(config.getProxyUsername(), config.getProxyPassword());
                                return response.request().newBuilder().header("Proxy-Authorization", credential).build();
                            });
                        }
                    }


                } catch (MalformedURLException e) {
                    throw new RuntimeException("Invalid proxy server configuration", e);
                }
            }

            if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) {
                httpClientBuilder.addNetworkInterceptor(chain -> {
                    Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent()).build();
                    return chain.proceed(agent);
                });
            }

            if (config.getTlsVersions() != null && config.getTlsVersions().length > 0) {
                ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                        .tlsVersions(config.getTlsVersions())
                        .build();
                httpClientBuilder.connectionSpecs(Arrays.asList(spec, CLEARTEXT));
            }
            return httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException("创建OKHTTPClient错误", e);
        }
    }

    /**
     * 生成安全套接字工厂,用于https请求的证书跳过
     */
    private static SSLSocketFactory createSSLSocketFactory(TrustManager[] trustAllCerts) {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ssfFactory;
    }

    private static TrustManager[] buildTrustManagers() {
        return 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[]{};
                    }
                }
        };
    }


    private static URL getProxyUrl(HttpClientConfig config) throws MalformedURLException {
        URL master = new URL(config.getMasterUrl());
        String host = master.getHost();
        if (config.getNoProxy() != null) {
            for (String noProxy : config.getNoProxy()) {
                if (host.endsWith(noProxy)) {
                    return null;
                }
            }
        }
        String proxy = config.getHttpsProxy();
        if (master.getProtocol().equals("http")) {
            proxy = config.getHttpProxy();
        }
        if (proxy != null) {
            return new URL(proxy);
        }
        return null;
    }

    /** -----------------------------------------------具体请求方法----------------------------------------------------**/


    /**
     * 发送post请求
     * @param isJsonPost true等于json的方式提交数据,类似postman里post方法的raw,false等于普通的表单提交
     * @param httpClientConfig httpclient配置类
     * @param paramMap 参数map
     * @return 返回的数据
     */
    public static String doPost(boolean isJsonPost,HttpClientConfig httpClientConfig,Map<String,String> paramMap){
        Response response = null;
        try {
            OkHttpClient client = getInstance(httpClientConfig);
            RequestBody requestBody;

            if (isJsonPost){
                String json = "";
                if (paramMap != null) {
                    json = JSONUtil.toJsonStr(paramMap);
                }
                requestBody = RequestBody.create(MediaType.parse("application/json"), json);
            }else {
                FormBody.Builder formBody = new FormBody.Builder();
                if (paramMap != null) {
                    paramMap.forEach(formBody::add);
                }
                requestBody = formBody.build();
            }

            Request.Builder builder = new Request.Builder();
            Request request = builder.url(httpClientConfig.getMasterUrl()).post(requestBody).build();
            response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                return  response.body().string();
            } else if (response.body() != null){
                logger.info(response.body().string());
                return null;
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (response != null){
                response.close();
            }
        }
        return null;
    }

    /**
     * 发送post请求(发送json格式的不是form表单格式的)
     * @param httpClientConfig httpclient配置类
     * @param map 参数map
     * @return 返回的数据
     */
    public static String doPost(HttpClientConfig httpClientConfig, Map<String,Object> map){
        Response response = null;
        try {
            OkHttpClient client = getInstance(httpClientConfig);

            String json = "";
            if (map != null) {
                json = JSONUtil.toJsonStr(map);
                System.out.println(json);
            }
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json);

            Request.Builder builder = new Request.Builder();
            Request request = builder.url(httpClientConfig.getMasterUrl()).post(requestBody).build();
            response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                return  response.body().string();
            } else if (response.body() != null){
                logger.info(response.body().string());
                return null;
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (response != null){
                response.close();
            }
        }
        return null;
    }


    /**
     * 携带token的post请求
     * @param isJsonPost true等于json的方式提交数据,类似postman里post方法的raw,false等于普通的表单提交
     * @param httpClientConfig httpclient配置类
     * @param paramMap 参数map
     * @param token token
     * @return 返回的数据
     */
    public static String doPostByToken(boolean isJsonPost,HttpClientConfig httpClientConfig, Map<String,String> paramMap, String token){
        Response response = null;
        try {
            OkHttpClient client = getInstance(httpClientConfig);
            RequestBody requestBody;

            if (isJsonPost){
                String json = "";
                if (paramMap != null) {
                    json = JSONUtil.toJsonStr(paramMap);
                }
                requestBody = RequestBody.create(MediaType.parse("application/json"), json);
            }else {
                FormBody.Builder formBody = new FormBody.Builder();
                if (paramMap != null) {
                    paramMap.forEach(formBody::add);
                }
                requestBody = formBody.build();
            }

            Request.Builder builder = new Request.Builder();
            Request request = builder.url(httpClientConfig.getMasterUrl()).header("Authorization", token).post(requestBody).build();
            response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                return  response.body().string();
            } else if (response.body() != null){
                logger.info(response.body().string());
                return null;
            }
        } catch (IOException e){
            e.printStackTrace();
        } finally {
            if (response != null){
                response.close();
            }
        }
        return null;
    }


    /**
     * 返回请求头
     * @param config httpclient配置类
     * @param paramMap 参数map
     * @return 响应头
     */
    public static Headers doLoginRequest(boolean isJsonPost,HttpClientConfig config, Map<String, String> paramMap) {
        Response response = null;
        try {
            OkHttpClient client = getInstance(config);
            RequestBody requestBody;

            if (isJsonPost){
                String json = "";
                if (paramMap != null) {
                    json = JSONUtil.toJsonStr(paramMap);
                }
                requestBody = RequestBody.create(MediaType.parse("application/json"), json);
            }else {
                FormBody.Builder formBody = new FormBody.Builder();
                if (paramMap != null) {
                    paramMap.forEach(formBody::add);
                }
                requestBody = formBody.build();
            }

            Request request = new Request.Builder().url(config.getMasterUrl()).post(requestBody).build();
            response = client.newCall(request).execute();
            if (response.isSuccessful() && response.body() != null) {
                return response.headers();
            } else if (response.body() != null){
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (response != null){
                response.close();
            }
        }
        return null;
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值