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

html一号店项目代码,项目一号店素材(html模板)

【实例简介】【实例截图】【核心代码】oneShop├── css│ ├── ShopShow.css│ ├── base.css│ ├── load.css│ ├── logo.css│ ├── register.css│ └── style.css├── detail.html├── images│ ├── Thumbs.db│ ├── a_close.png│...

weixin_35390150的博客 4989

油气井管柱力学发展

油气井管柱力学发展 1 石油管柱力学问题的发复杂性 1)油气管柱动力学的非线性 钻井中钻柱在重力、钻压、扭矩、钻井液浮力和井壁约束等作用下,产生三维变形。一方面随井眼轴线的弯曲而弯曲,这一变形被称为管柱的初位移;另一方面,管柱在运动过程中相对井眼轴线也有变形,这种变形被称为计算位移。管柱大变形主要表现在初位移部分,计算位移相对很小。大曲率井眼中管柱产生大挠度,但管柱很长且柔软性较好,变形一般仍保持...

weixin_43831995的博客 950

基于 httpclient 4.5版本的 http工具类

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

weixin_39643007的博客 942

IEEE论文接收后,收到Proof邮件别慌!手把手教你48小时内搞定校样(附详细截图)

本文详细解析了IEEE论文接收后Proof校样的全流程,从邮件关键信息解码到精准修改标注,提供48小时内高效完成校样的实战指南。涵盖登录技巧、文件验证、修改标注黄金法则及九宫格检查清单,帮助作者避免常见错误,确保论文顺利发表。

weixin_30652491的博客 563

Httpclient5工具类

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

shenbururen的博客 5138

centos7 清理缓存

一、系统环境 系统版本 CentOS Linux release 7.3.1611 (Core) 内核版本 Linux xx-user 3.10.0-514.el7.x86_64 #1 SMP 背景 服务器分配的账号是普通用户,只能执行sudo命令 二、缓存查看及基本概念 查看内存使用情况 [user01@xx-user ~]$ free -h total used free shared buff/cache availabl

sunzq55的博客 4004

Git Worktree + Claude Code:多终端并发开发完全实战

深入讲解如何使用 Git Worktree 配合多终端 Claude Code 实现并发开发,通过实战案例展示如何在 Android 开发中提升 2-3 倍效率,彻底告别等待 AI 的问题。

Cheson的专栏 1205

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

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

m0_52767002的博客 8838

[QMT量化交易小白入门]-六十九、ETF动量评分策略,历史年化收益率107%

C . bar_date } 跳过') returnC . bar_date } 跳过') returnC . bar_date } 跳过') return作用:如果当前不是回测模式且不是最后一根K线,则记录日志并跳过本次任务。这是为了避免在实时交易中对尚未完成的数据进行处理。

木头大左的博客 2229

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

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

IOsetting的专栏 5130

【数字孪生与仿真技术】05:从原理到实战:MATLAB/Simulink在航空航天GNC系统开发中的深度解析(含全流程代码与认证指南)

摘要:本文系统阐述MATLAB/Simulink在航空航天制导、导航与控制(GNC)系统开发中的核心应用。通过解析GNC系统高保真动力学建模、多源导航传感器融合、鲁棒控制算法设计等关键技术原理,结合Virgin Orbit运载火箭、CubeSat等真实案例,展示从需求分析、模型搭建、仿真验证到代码生成与认证的完整开发流程。文中提供1200余行关键代码、8个可复用Simulink模型及详细执行结果展示,涵盖DO-178C认证支持、实时性能优化等工业级开发规范,为航空航天工程师、科研人员提供可落地的参考方案。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1656

① Django手把手从零开发个人博客-前言

手把手教你从零开始玩转手把手教你从零开始玩转Django,全面学习并了解django的运行机制、开发全流程及线上部署。Django,全面学习并了解django的运行机制、开发全流程及线上部署。 专栏介绍 本套教程遵循Django的设计思想,开门见山,快速切入主题,拒绝拖沓,在实战中学习每一个知识点,提高学习的趣味性以及个人成就感,并且能快速将所学运用到实际项目中。 将从零手把手带着你一步步完成博客的每一个功能,通过实现博客文章列表页、文章详情页、作者页面等功能来学习和了解django的视图查询模块相关知.

轻编程的博客 513

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

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

基于 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

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

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

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

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、付费专栏及课程。

余额充值