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

torchsparse安装

torchsparse安装以及安装失败原因分析和解决

AI_BING_的博客 1万+

Matlab Copula函数实战:从金融风控到数据建模的5个应用场景

本文深入探讨了Matlab Copula函数在金融风控与数据建模中的五大实战应用场景,包括投资组合风险价值计算、信用违约相关性建模、跨市场套利策略优化等。通过具体代码示例和数据分析,展示了Copula模型在捕捉复杂依赖关系方面的优势,为金融风险管理和量化分析提供实用工具。

weixin_29090677的博客 425

基于 httpclient 4.5版本的 http工具类

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

weixin_39643007的博客 942

告别Keil/IAR:在VSCode中用CMake+Clangd打造丝滑的STM32开发环境(附完整配置)

本文详细介绍了如何在VSCode中使用CMake和Clangd搭建高效的STM32开发环境,替代传统的Keil/IAR工具。通过完整的配置指南和快速开发技巧,帮助开发者实现轻量级、高度可定制的现代化开发流程,显著提升STM32项目的开发效率。

weixin_26843605的博客 164

Httpclient5工具类

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

shenbururen的博客 5138

【物联网毕设】多模态智能门禁系统设计(STM32+人脸识别+蓝牙联动)

本文详细介绍了基于STM32的多模态智能门禁系统设计,整合了人脸识别、蓝牙联动、RFID和密码等多种开锁方式。文章从硬件选型、电路设计、嵌入式软件编程到手机APP开发,提供了完整的毕设实现方案与调试指南,帮助物联网与嵌入式方向的学生构建一个功能全面、可扩展的智能门禁系统。

rain6的博客 247

LT9611EX芯片实战:如何用双端口MIPI转HDMI1.4打造高清播放器(附配置代码)

本文详细介绍了如何使用龙迅半导体的LT9611EX芯片实现双端口MIPI转HDMI1.4的高清播放器开发。内容涵盖芯片特性、硬件设计要点、寄存器配置技巧及完整代码实现,特别适合嵌入式视频处理应用,如机顶盒和便携式媒体播放器。

weixin_29256771的博客 322

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

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

m0_52767002的博客 8838

生成模型实战 | MuseGAN详解与实现

人工智能音乐生成领域已引起了广泛关注,MuseGAN 是其中一个重要的模型。本节我们将使用 JSB Chorales 数据集来训练 MuseGAN,该数据集包含巴赫创作的四音轨合唱曲。在生成图像时,生成器使用的是来自潜在空间的单一噪声向量来生成不同格式的内容;而在 MuseGAN 中,生成器将使用四个噪声向量来生成一段音乐,旨在增强音乐生成过程中的可控行和多样性。每个噪声向量代表音乐的不同方面,通过单独调整这些向量,模型可以生成更复杂、更细腻的音乐作品。

盼小辉丶的博客 6564

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

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

IOsetting的专栏 5130

一分钟了解 “提示词工程”、“上下文工程”、“驾驭工程”

在大模型刚刚进入大众视野的初期,开发者面临的最大挑战是如何让模型听懂人类的指令。这一阶段被称为提示词工程时代。其核心思想非常直观:通过精心设计输入的文本提示,引导模型输出符合预期的结果。这一时期的开发者更像是“提示词巫师”,他们热衷于寻找所谓的“魔法咒语”。典型的技巧包括角色设定、思维链、少样本学习以及输出格式约束。例如,仅仅在问题前加上一句“请一步步思考”,模型的推理能力往往就能得到显著提升。然而,随着应用场景的复杂化,提示词工程的局限性逐渐暴露。

h a 6 6 6 c k 为 你解决复杂难题! 569

180.在 Vue3 中使用 OpenLayers 实现多个多边形的绘制、编辑、删除与清空

【摘要】本文介绍如何在Vue3+TypeScript环境下使用OpenLayers实现多边形地图交互功能。通过Composition API封装核心逻辑,实现了多边形绘制、编辑、删除及清空等操作。关键技术包括:使用VectorLayer管理图形数据,Draw/Modify/Select交互控制,以及通过ref()管理交互状态。文中提供了完整代码示例,并解决了交互对象叠加问题,为开发GIS应用提供了基础模块。该方案支持扩展为数据库存储、后端交互等高级功能。

小彭的博客 769

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

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

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

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

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

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

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

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

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

余额充值