Java使用Apache的HttpClient组件发送https请求
如果我们直接通过普通的方式对https的链接发送请求,会报一个如下的错误:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:702)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:122)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140)
at java.io.FilterOutputStream.flush(FilterOutputStream.java:140)
at org.apache.commons.httpclient.methods.StringRequestEntity.writeRequest(StringRequestEntity.java:146)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at com.xxx.yyy.portal.utils.HttpRequest.exeRequest(HttpRequest.java:148)
at com.xxx.yyy.portal.utils.HttpDemo1.main(HttpDemo1.java:15)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:385)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
at sun.security.validator.Validator.validate(Validator.java:260)
at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:326)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:126)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1323)
... 20 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
... 26 more
这个错表示https的链接需要证书验证,普通的方式不能完成https链接的请求。
直接给出代码,封装成工具类,提供了两种实现方式。
第一种完成使用Java自身的Api实现;
第二种使用Apache的httpclient相关jar包实现,注意需要引入apache httpclient的相关依赖包,如下:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.6</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.3.1</version>
</dependency>
工具类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils; public class HttpRequest { public static String exeHttpsRequest(String URL, String message, String token) {
String body = "";
CloseableHttpClient client = null;
try {
// 采用绕过验证的方式处理https请求
SSLContext sslcontext = createIgnoreVerifySSL();
// 设置协议http和https对应的处理socket链接工厂的对象
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create()
.register("http", PlainConnectionSocketFactory.INSTANCE)
.register("https", new SSLConnectionSocketFactory(sslcontext,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
HttpClients.custom().setConnectionManager(connManager); // 创建自定义的httpclient对象
client = HttpClients.custom().setConnectionManager(connManager).build();
// CloseableHttpClient client = HttpClients.createDefault(); // 创建post方式请求对象
HttpPost httpPost = new HttpPost(URL); // 指定报文头Content-type、User-Agent
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Authorization", "Bearer " + token);
httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
StringEntity stringEntity = new StringEntity(message, "UTF-8");
stringEntity.setContentType("application/json"); httpPost.setEntity(stringEntity);
// 执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost); // 获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
// 按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, "UTF-8");
} EntityUtils.consume(entity);
// 释放链接
response.close();
// System.out.println("body:" + body);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return body; } private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sc = SSLContext.getInstance("SSLv3"); // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
X509TrustManager trustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
} @Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
String paramString) throws CertificateException {
} @Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}; sc.init(null, new TrustManager[] { trustManager }, null);
return sc;
} private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
} public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
} private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
} public static String sendSSLPostRequest(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
// URLEncoder.encode(param,"UTF-8"); URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Encoding", "utf-8");
conn.setRequestProperty("Charsert", "utf-8");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
if (conn instanceof HttpsURLConnection) {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
((HttpsURLConnection) conn).setSSLSocketFactory(sc.getSocketFactory());
((HttpsURLConnection) conn).setHostnameVerifier(new TrustAnyHostnameVerifier());
}
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8")); out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("POST 请求异常!!!" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
} return result;
}
}
全文完。
原文地址:
https://www.cnblogs.com/poterliu/p/9373478.html
Java使用Apache的HttpClient组件发送https请求的更多相关文章
- HttpClient 之 发送Https请求
HttpClient包是一个优秀的Http请求的开源jar. 本文Http工具类的封装基于HttpClient,封装后的工具类支持Https请求. 但是由于项目的需要快速的实现,以下代码还可能会有点过 ...
- 使用HttpClient发送HTTPS请求以及配置Tomcat支持SSL
这里使用的是HttpComponents-Client-4.1.2 package com.jadyer.util; import java.io.File; import java.io.FileI ...
- 简单粗暴套娃模式组json发送https请求
各位童鞋大家好,向来简单粗暴的铁柱兄给大家来玩一手套娃模式来组Json数据,不说别的,无脑套. 当然,这一手比较适合临场用一下,若长期用的话建议搞一套适用的框架,只管set就好了.话不多说开始上课. ...
- org.apache.httpcomponents httpclient 发起HTTP JSON请求
1. pom.xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactI ...
- 【传输协议】发送https请求,由于客户端jdk版本过高,服务端版本低。导致异常:javax.net.ssl.SSLHandshakeException: Server chose SSLv3, but that protocol version is not enabled or not supported by the client.
本地环境jdk为1.8,服务器使用jdk版本未知.但发送https请求,抛出如下异常,解决方案. 一:发送异常内容如下 javax.net.ssl.SSLHandshakeException: Ser ...
- .Net Core 发送https请求/.net core 调用数字证书 使用X509Certificate2
.Net Core 发送https请求 .net core 调用数字证书 使用X509Certificate2 .NET下面的 .netfromwork使用和asp.net core下使用方式不一样 ...
- 【转载】JMeter学习(三十六)发送HTTPS请求
Jmeter一般来说是压力测试的利器,最近想尝试jmeter和BeanShell进行接口测试.由于在云阅读接口测试的过程中需要进行登录操作,而登录请求是HTTPS协议.这就需要对jmeter进行设置. ...
- Web Server 使用WebClient 发送https请求 The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel
使用WebClient 发送https请求 使用WebClient发送请求时,并且是以https协议: WebClient webClient = new WebClient(); string re ...
- JMeter学习(三十六)发送HTTPS请求(转载)
转载自 http://www.cnblogs.com/yangxia-test Jmeter一般来说是压力测试的利器,最近想尝试jmeter和BeanShell进行接口测试.由于在云阅读接口测试的过程 ...
随机推荐
- BZOJ 1433 && Luogu P2055 [ZJOI2009]假期的宿舍 匈牙利算法
刚学了匈牙利正好练练手(我不会说一开始我写错了)(怕不是寒假就讲了可是我不会) 把人看做左部点,床看作右部点 建图:(!!在校相当于有床,不在校相当于没有床 但是要来学校) 1.在校的 不走的人 自己 ...
- Hdu1015&&寒假作业第二组I题
题意是A-Z对应1-26,然后给个目标数字和字符串,看看字符串里的某5个字符的组合能不能使v - w^2 + x^3 - y^4 + z^5 = target等式成立,其实多写几个循环也可以达到目的, ...
- NET Core使用Quartz
NET Core使用Quartz 一.前言运用场景 Quartz.Net是一个强大.开源.轻量的作业调度框架,在平时的项目开发当中也会时不时的需要运用到定时调度方面的功能,例如每日凌晨需要统计前一天的 ...
- 爬虫(ProxyHandler)——代理
工具:python3 步骤: 1)使用ProxyHandler()构建httpproxy_handler对象 2)使用build_opener(httpproxy_handler)构建opener 3 ...
- 056 Merge Intervals 合并区间
给出一个区间的集合, 请合并所有重叠的区间.示例:给出 [1,3],[2,6],[8,10],[15,18],返回 [1,6],[8,10],[15,18].详见:https://leetcode.c ...
- Zeppelin的入门使用系列之使用Zeppelin运行shell命令(二)
不多说,直接上干货! 前期博客 Zeppelin的入门使用系列之创建新的Notebook(一) 接下来,我将以ml-100k数据集,示范如何使用Spark SQL进行数据分析与数据可视化 因为 [ha ...
- 使用OAuth保护REST API并使用简单的Angular客户端
1.概述 在本教程中,我们将使用OAuth保护REST API并从简单的Angular客户端使用它. 我们要构建的应用程序将包含四个独立的模块: 授权服务器 资源服务器 UI implicit - 使 ...
- Fedora12下yum安装低版本gcc
1.Fedora12下gcc位置及其版本如下: 2.根据需要,要安装低版本的gcc,直接用"yum install gcc"安装时默认是安装最新版本的gcc,如下: 3.可先通过& ...
- 微信支付(java版本)_统一下单
最近工作接触到微信支付,刚开始解决微信支付很神秘,接触之后发现并没有那么神秘,就是有很多坑,在开发的时候需要注意,整理出来: 1.准备工作 首先需要登录微信支付公众平台阅读接口文档,地址:https: ...
- Java thymeleaf模板获取资源文件的内容
我们在某些时候可能需要获取配置文件properties中的配置信息,而不需要用Java传给模板,在模板中就可以直接获取 我们需要在resources/下定义国际化配置文件即可,注意名称必须中messa ...