惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
博客园 - 司徒正美
宝玉的分享
宝玉的分享
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
月光博客
月光博客
博客园 - 【当耐特】
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
博客园 - 聂微东
小众软件
小众软件
Hugging Face - Blog
Hugging Face - Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Apple Machine Learning Research
Apple Machine Learning Research
V
V2EX
Jina AI
Jina AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
雷峰网
雷峰网
博客园 - 叶小钗
量子位
IT之家
IT之家

Liu Zijian's Blog | 一个技术博客

使用Certbot自动续签HTTPS证书 使用Filebeat采集Nginx日志到ES Python的协程 Python中的异常 Python中的类和对象 Python的函数 Python的数据结构,推导式、迭代器和生成器 Spring AI集成多模态模型 LangChain4j多模态 LangChain Tools工具使用 Python中的模块和包 Python全局环境和虚拟环境(venv) LangChain Prompt提示词工程 LangChain4j Tools工具使用 基于Dify搭建AI智能体应用 LangChain4j RAG检索增强生成 Spring AI实现MCP Server Spring AI集成MCP Client LangChain4j Prompt提示词工程 Spring AI使用知识库增强对话功能 Spring AI实现一个智能客服 Spring AI实现一个简单的对话机器人 实现MinIO数据的每日备份 自己实现一个DNS服务 简单理解AI智能体 大模型和大模型应用 LangChain开篇 LangChain4j开篇 一个解析Excel2007的POI工具类 DataPermissionInterceptor源码解读
一个通用的CloseableHttpClient工厂类
Liu Zijian · 2023-01-01 · via Liu Zijian's Blog | 一个技术博客

一个CloseableHttpClient工厂,基于java知名开源库apache-httpclient,能够忽略SSL,并且超时和状态异常时可以重试

<dependencies>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.9</version>
    </dependency>

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.9</version>
    </dependency>

</dependencies>
package util;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpResponse;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import java.net.SocketTimeoutException;


@Slf4j
public class HttpClientUtil {

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            SSLContext sslContext = sslContextBuilder.loadTrustMaterial(null, (chain, authType) -> true).build();

            SSLConnectionSocketFactory ssl = new SSLConnectionSocketFactory(
                    sslContext,
                    new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"},
                    null,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);


            return HttpClients.custom()
                    .setSSLSocketFactory(ssl)
                    .setRetryHandler((e, executionCount, context) -> {
                        if (executionCount <= 20) {
                            if (e instanceof NoHttpResponseException
                                    || e instanceof ConnectTimeoutException
                                    || e instanceof SocketTimeoutException
                                    || e instanceof SSLHandshakeException) {
                                log.info("{} 异常, 重试 {}", e.getMessage(), executionCount);
                                return true;
                            }
                        }

                        return false;
                    })
                    .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                        @Override
                        public boolean retryRequest(HttpResponse response, int executionCount, HttpContext context) {
                            int statusCode = response.getStatusLine().getStatusCode();
                            if (statusCode != 200) {
                                if (executionCount <= 20) {
                                    log.info("{} 状态码异常, 重试 {}", statusCode, executionCount);
                                    return true;
                                }

                            }
                            return false;
                        }

                        @Override
                        public long getRetryInterval() {
                            return 0;
                        }
                    })
                    .build();
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}