HttpClient4.5 SSL访问工具类

HttpClient高级进阶-SSL 简介 本文将展示如何使用“全部接受”SSL支持配置Apache HttpClient 4。目标很简单 - 使用没有有效证书的HTTPS URL。 SSLPeerUnverifiedException 如果不使用HttpClient配置SSL ,以下测试(使用HTTPS URL)将失败: public class RestClientLiveManualTest { @Test(expected = SSLPeerUnverifiedException.class) publ 阅读详情

要从网上找一个HttpClient SSL访问工具类太难了,原因是HttpClient版本太多了,稍有差别就不能用,封装了一个访问HTTPS并绕过证书工具类。

主要是基于新版本HttpClient 4.5:

/**
解决httpClient对https请求报不支持SSLv3问题.
JDK_HOME/jrebcurity/java.security 文件中注释掉:
jdk.certpath.disabledAlgorithms=MD2
jdk.tls.disabledAlgorithms=DSA(或jdk.tls.disabledAlgorithms=SSLv3)
*/
public class HttpsUtil {
    public static CloseableHttpClient createClient() throws Exception{
        TrustStrategy trustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] xc, String msg)
                    throws CertificateException {
                return true;
            }
        };
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(trustStrategy);
        HostnameVerifier hostnameVerifierAllowAll = new HostnameVerifier() {
            @Override
            public boolean verify(String name, SSLSession session) {
                return true;
            }
        };
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                builder.build(), new String[] { "SSLv2Hello", "SSLv3", "TLSv1",
                        "TLSv1.1", "TLSv1.2" }, null, hostnameVerifierAllowAll);
         
        HttpRequestRetryHandler myRetryHandler = new HttpRequestRetryHandler() {
            public boolean retryRequest(
                    IOException exception,
                    int executionCount,
                    HttpContext context) {
                //重试设置
                if (executionCount >= 5) {
                    // Do not retry if over max retry count
                    return false;
                }
                if (exception instanceof InterruptedIOException) {
                    // Timeout
                    return false;
                }
                if (exception instanceof UnknownHostException) {
                    // Unknown host
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {
                    // Connection refused
                    return false;
                }
                if (exception instanceof SSLException) {
                    // SSL handshake exception
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
                if (idempotent) {
                    return true;
                }
                return false;
            }
        };     
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(120000)
                .setSocketTimeout(120000)//超时设置
                .build();
        CloseableHttpClient httpclient = HttpClients.custom()
                .setSSLSocketFactory(sslsf)
                .setRetryHandler(myRetryHandler)//重试设置
                .setDefaultRequestConfig(requestConfig)
                .build();
        return httpclient;
    }
     
    public static String get(String url) throws Exception {
        return get(url,null,null);
    }
         
    public static String get(String url,Map<String, String> header,Map<String, String> outCookies) throws Exception {
        String body = "";      
        String Encoding ="utf-8";      
        CloseableHttpClient client = createClient();
        try {
            CookieStore cookieStore = new BasicCookieStore();          
            HttpClientContext localContext = HttpClientContext.create();
            localContext.setCookieStore(cookieStore);
            // 创建get方式请求对象
            HttpGet httpGet = new HttpGet(url);
            if(header!=null){
                if(header.get("Accept")!=null) httpGet.setHeader("Accept", header.get("Accept"));
                if(header.get("Cookie")!=null) httpGet.setHeader("Cookie", header.get("Cookie"));
                if(header.get("Accept-Encoding")!=null) httpGet.setHeader("Accept-Encoding", header.get("Accept-Encoding"));
                if(header.get("Accept-Language")!=null) httpGet.setHeader("Accept-Language", header.get("Accept-Language"));
                if(header.get("Host")!=null) httpGet.setHeader("Host", header.get("Host"));
                if(header.get("User-Agent")!=null) httpGet.setHeader("User-Agent", header.get("User-Agent"));
                if(header.get("x-requested-with")!=null) httpGet.setHeader("x-requested-with", header.get("x-requested-with"));
                if(header.get("Encoding")!=null) Encoding =header.get("Encoding");
            }
            System.out.println("请求地址:" + url);
            // 执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpGet,localContext);         
            // 获取结果实体
            try {
                // 如果需要输出cookie
                if(outCookies!=null){
                    List<Cookie> cookies = cookieStore.getCookies();                 
                    for (int i = 0; i < cookies.size(); i++) {
                        outCookies.put(cookies.get(i).getName(),cookies.get(i).getValue());
                    }
                }
                HttpEntity entity = response.getEntity();
                System.out.println("返回:" + response.getStatusLine());
                if (entity != null) {
                    // 按指定编码转换结果实体为String类型
                    body = EntityUtils.toString(entity, Encoding);
                    // System.out.println("返回:"+body);
                }
            } finally {
                response.close();
            }
        } finally {
            client.close();
        }
        return body;
    }
 
    public static String post(String url, Map<String, String> params)
            throws Exception {
        return post(url, params, null,null);
    }
     
    public static String post(String url, Map<String, String> params, Map<String, String> header,Map<String, String> outCookies)
            throws Exception {
        String body = "";
        String encoding ="utf-8";
        String contentType="text/html";
        CloseableHttpClient client = createClient();
        CookieStore cookieStore = new BasicCookieStore();          
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setCookieStore(cookieStore);
        try {
            // 创建post方式请求对象
            HttpPost httpPost = new HttpPost(url);
            if(header!=null){
                if(header.get("Accept")!=null) httpPost.setHeader("Accept", header.get("Accept"));
                if(header.get("Cookie")!=null) httpPost.setHeader("Cookie", header.get("Cookie"));             
                if(header.get("Accept-Encoding")!=null) httpPost.setHeader("Accept-Encoding", header.get("Accept-Encoding"));
                if(header.get("Accept-Language")!=null) httpPost.setHeader("Accept-Language", header.get("Accept-Language"));
                if(header.get("Host")!=null) httpPost.setHeader("Host", header.get("Host"));
                if(header.get("User-Agent")!=null) httpPost.setHeader("User-Agent", header.get("User-Agent"));
                if(header.get("x-requested-with")!=null) httpPost.setHeader("x-requested-with", header.get("x-requested-with"));
                if(header.get("Encoding")!=null) encoding =header.get("Encoding");
                if(header.get("Content-Type")!=null) contentType =header.get("Content-Type");
            }
            // 装填参数
            if (contentType.equalsIgnoreCase("text/html")) {
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                if (params != null) {
                    for (Entry<String, String> entry : params.entrySet()) {
                        nvps.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps, encoding));
            }
            //JOSN格式参数
            if (contentType.equalsIgnoreCase("application/json")) {
                StringEntity myEntity = new StringEntity(JSON.toJSONString(params.get("data")),
                        ContentType.create("application/json", "UTF-8"));
                httpPost.setEntity(myEntity);
            }
            System.out.println("请求地址:" + url);
            // 执行请求操作,并拿到结果(同步阻塞)
            CloseableHttpResponse response = client.execute(httpPost,localContext);
            // 获取结果实体
            try {
                // 如果需要输出cookie
                if(outCookies!=null){
                    List<Cookie> cookies = cookieStore.getCookies();                 
                    for (int i = 0; i < cookies.size(); i++) {
                        outCookies.put(cookies.get(i).getName(),cookies.get(i).getValue());
                    }
                }
                HttpEntity entity = response.getEntity();
                System.out.println("返回:" + response.getStatusLine());
                if (entity != null) {
                    // 按指定编码转换结果实体为String类型
                    body = EntityUtils.toString(entity, encoding);
                    // System.out.println("返回:"+body);
                }
            } finally {
                response.close();
            }
        } finally {
            client.close();
        }
        return body;
    }
    public static void main(String[] args) throws Exception {
        String body =get("https://www.baidu.com/");
        System.out.println(body);
    }
}


Apache HttpClient 4.5实现https 没什么,就是记录个代码。 全部信任的 import org.apache.commons.collections.MapUtils; import org.apache.http.*; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPos... 阅读详情

相关推荐

Apache HttpClient 4和5访问没有有效证书的HTTPS

本文将展示如何配置Apache HttpClient 4和5以支持“接受所有”SSL。目标很简单——访问没有有效证书的HTTPS URL。

疯一样的码农 1211

HTTPclient(4.5.13)请求https网页

本文使用的HTTPclient版本是4.5.13 import java.io.IOException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import org.apache.hc.client5.http.ClientProtocolException; import org.apache.hc

qq_37917691的博客 2387

基于httpclient4.5.6实现ssl双向访问、单向访问

1.引入包 &lt;dependency&gt;     &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt;     &lt;artifactId&gt;httpclient&lt;/artifactId&gt;     &lt;version&gt;4.5.6&lt;/version&gt; &lt;/dependency&

luoni186的专栏 1787

httpclient封装工具类

前言在日常开发中,我们经常需要通过http协议去调用网络内容,虽然java自身提供了net相关工具包,但是其灵活性和功能总是不如人意,于是有人专门搞出一个httpclient类库,来方便进行Http操作。对于httpcore的源码研究,我们可能并没有达到这种层次,在日常开发中也只是需要的时候,在网上百度一下,然后进行调用就行。在项目中对于这个工具类库也许没有进行很好的封装。在哪里使用就写在哪些,很多

爱琴孩的博客 2万+

Java使用HttpClient5实现发送HTTP请求

HttpClient5 是 Apache HttpComponents 项目中的一个重要组件,它是一个功能齐全且高度可定制的 HTTP 客户端库,专门用于发送 HTTP 请求、处理 HTTP 响应并支持各种 HTTP 协议特性。内置的连接池机制能提高并发处理性能,减少资源消耗。内置 Cookie 管理功能,能够自动处理服务端返回的 Cookie 并在后续请求中使用,模拟浏览器行为。HttpClient5 的设计高度模块化,用户可以根据需要对连接管理、重定向策略、请求重试策略、代理设置等进行灵活定制。

pan_junbiao的博客 2042

【Http】Apache HttpClient 4.5实现https

全部信任的 import org.apache.commons.collections.MapUtils; import org.apache.http.*; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.config.Registry; import org.apache.http.confi.

九师兄 2743

httpClient4.5配置SSL绕过https证书,httpClient过时替代方法

httpClient private HttpClient sslClient(){ try { HttpClient httpclient = new DefaultHttpClient(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, null, null); SSL...

远方 3992

httpclient4.5 绕过ssl认证文件访问

这是一个关于httpclient4.5访问https网站的例子,可以绕过ssl认证直接访问

HttpClient如何访问需要提交客户端证书的SSL服务

@TOC测试页面 欢迎使用Markdown编辑器 你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。 新的改变 我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客: 全新的界面设计 ,将...

toilerchen的博客 2678

Windows Server下OnlyOffice Workspace社区版安装避坑指南(含局域网邮箱配置)

本文详细介绍了在Windows Server环境下部署OnlyOffice Workspace社区版的完整流程,特别针对企业内网环境中的邮箱配置和端口冲突等常见问题提供了实用解决方案。通过硬件资源配置建议、软件环境检查清单以及内网邮箱系统搭建方案对比,帮助用户高效搭建企业级协作平台,实现团队协作的无缝对接。

weixin_29231263的博客 449

Globus数据下载全攻略:从零配置到批量下载大文件(附常见问题解决)

本文详细介绍了Globus数据下载的全流程,从零配置到批量下载大文件的实用技巧,包括环境准备、高级传输策略、性能优化及常见问题解决方案。Globus作为科研数据的高效传输工具,通过并行流传输和自动校验技术,显著提升大规模数据传输的效率和可靠性。

u9v0w的博客 662

基于 httpclient 4.5版本的 http工具类

1.在pom文件中添加 <dependencies> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2...

weixin_39643007的博客 942

同花顺 python量化交易_开启量化第一步!同花顺iFinD数据接口免费版简易操作教程...

来源:雪球App,作者: 同花顺-iFinD,(https://xueqiu.com/6706494343/141951051)金融市场波动频繁,投资往往会夹杂非理性的情绪。而量化交易,旨在以先进的数学模型替代人为的主观判断,利用计算机技术从庞大的历史数据中海选能带来超额收益的多种“大概率”事件以制定策略,辅助投资者进行理性投资。不过计算机分析存在一定的技术门槛,有没有简单易学的量化交易方式,能够...

weixin_35911805的博客 2万+

Httpclient5工具类

一、说明 就是一个工具类,使用了httpclient5-fluent流式组件,其实单纯用这个组件已经很方便了。只是有一些配置要自定义,所以再封装一层。 注释懒得加了,看参数名应该就明白了。有哪里不对的欢迎指正。 二、maven引用 这里流式组件已经依赖了 httpclient5了,所以不需要再单独引用。 hutool工具包太好用了,我所有项目都会引用。hutool里也有httputil,只是不支持连接池。 <dependency> &lt..

shenbururen的博客 5138

osgEarth实战:5分钟搞定3DTiles模型加载(附完整配置代码)

本文提供了一份osgEarth加载3DTiles模型的实战指南。通过详解核心Earth文件配置与精简的C++集成代码,帮助开发者快速在三维地球场景中集成倾斜摄影与BIM等海量模型,并分享了性能调优与常见问题排查技巧,有效提升开发效率。

jjj34的博客 479

基于深度学习的商品标签识别系统:UI界面 + YOLOv8/v7/v6/v5代码 + 训练数据集

基于YOLO系列模型的商品标签识别系统能够有效解决商品信息提取的自动化问题。通过合理的数据集准备、模型训练和UI设计,我们可以实现一个功能强大的商品标签识别系统。希望本文提供的内容能够为大家提供有价值的帮助。

YOLO 474

HttpUtils工具类(二)Apache HttpClient 5 使用详细教程

Apache HttpClient 5 是一个功能齐全且高度可定制的 HTTP 客户端库, 其专门用于发送 HTTP 请求、处理 HTTP 响应并支持各种 HTTP 协议特性。特别适合处理复杂的 HTTP 请求需求,如多协议支持、认证、连接池、代理等。它适合中大型项目或需要高级 HTTP 特性的应用开发。

m0_52767002的博客 8838

Python 爬虫实战:在房天下抓取房产信息,分析房价走势

通过本次 Python 爬虫实战,我们成功地从房天下爬取了房产信息,并进行了存储、处理、分析和可视化展示。在这个过程中,我们不仅掌握了爬虫技术的基本应用,还学会了如何对动态加载的数据进行处理和分析。然而,本次爬虫任务也存在一些局限性,例如仅爬取了部分区域的房产数据,且未对房产的图片和视频内容进行分析。在未来的工作中,我们可以进一步优化爬虫程序,爬取更多区域的房产数据,并深入分析房产的多媒体内容、用户行为模式等,为购房者和房地产从业者提供更有价值的数据支持。

u014481728的博客 1367

Apache HttpClient 5 笔记: SSL, Proxy 和 Multipart Upload

HttpClient 版本已经到 5.2.1 了. 在版本4中的一些方法已经变成 deprecated, 于是将之前的工具类升级一下, 顺便把中间遇到的问题记录一下

IOsetting的专栏 5130

Python爬虫实战:使用最新技术抓取采购网招标公告信息

本文将详细介绍如何使用Python最新爬虫技术构建一个高效的采购网招标公告信息抓取系统。我们将从爬虫基础概念讲起,逐步深入到高级技巧,包括异步处理、反爬虫对策、数据解析与存储等,并提供完整的代码实现。本文旨在为读者提供一套完整的网络数据采集解决方案,适用于各类政府采购平台和商业招标网站。网络爬虫(Web Crawler)是一种自动抓取互联网信息的程序或脚本,它们按照一定的规则,自动地浏览万维网并提取所需数据。在现代商业环境中,爬虫技术广泛应用于价格监控、竞争情报收集、市场研究等领域。

2201_76125261的博客 1621

【2025国赛C题】高教社杯全国大学生数学建模竞赛C题思路+代码+论文

【2025国赛C题】高教社杯全国大学生数学建模竞赛C题思路+代码+论文

订阅付费专栏Matlab(奶茶价版),可赠送奶茶价版付费专栏指定代码1份; 2903

HttpClient的ssl方式发送请求

最近因为项目需要,需要以rest方式和第三方平台交互,由于需要ssl方式连接,所以记录一下: maven依赖如下: &lt;dependency&gt; &lt;groupId&gt;org.apache.httpcomponents&lt;/groupId&gt; &lt;artifactId&gt;httpclient&lt;/artifactId&gt; &...

whp404的博客 5973

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

基于 HttpClient 4.5 的 HttpClientUtils

欢迎关注微信公众号:PM实验室 我编写工具类所参考的文档 pache HttpClient: http://hc.apache.org/httpcomponents-client-ga/index.html 中文翻译教程: https://www.yiibai.com/apache_httpclient stackoverflow 关于SSL的讨论: https://stackoverfl...

野指针er 1524

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

apache HttpClient 4.5 工具类

package tools; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.htt...

love13135816的专栏 375

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

HttpClient 4.5.x 之后 Deprecated 废弃API 的替代对应策略

在《扫清盲点,如何正确的从HttpClient 3.x系统升级到HttpClient 4.x》一文中已经详细的指明 HttpClient 3.x 迁移到 HttpClient 4.x 相关的变更点以及升级替换策略。本文针对HttpClient 4.5.x 之后 被 @Deprecated 注解后的废弃 / 过期 API(SSL证书验证相关),如何进行替换进行相关总结。 1.   针对 SSLCo...

我在山城重庆,我希望能为这片软件沙漠地带贡献自己的一滴水,Stay tuned! 9764
上一篇: 阿里云申请云盾免费SSL证书(https)
下一篇: 一、spring-cloud-simple 地址
VirusFu
博客等级 码龄21年 51粉丝 79原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值