今天用java HttpClients写爬虫在访问某Https站点报如下错误:

sun.security.validator.ValidatorException: PKIX path building failed...

网上找了找解决方案,看到这篇博客:http://www.oschina.net/question/12_19249

http://www.oschina.net/code/snippet_12_4092

经测试,解决问题,这里做个记录。

/*
* Copyright 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* - Neither the name of Sun Microsystems nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/ import java.io.*;
import java.net.URL; import java.security.*;
import java.security.cert.*; import javax.net.ssl.*; public class InstallCert { public static void main(String[] args) throws Exception {
String host;
int port;
char[] passphrase;
if ((args.length == ) || (args.length == )) {
String[] c = args[].split(":");
host = c[];
port = (c.length == ) ? : Integer.parseInt(c[]);
String p = (args.length == ) ? "changeit" : args[];
passphrase = p.toCharArray();
} else {
System.out.println("Usage: java InstallCert <host>[:port] [passphrase]");
return;
} File file = new File("jssecacerts");
if (file.isFile() == false) {
char SEP = File.separatorChar;
File dir = new File(System.getProperty("java.home") + SEP
+ "lib" + SEP + "security");
file = new File(dir, "jssecacerts");
if (file.isFile() == false) {
file = new File(dir, "cacerts");
}
}
System.out.println("Loading KeyStore " + file + "...");
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close(); SSLContext context = SSLContext.getInstance("TLS");
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
socket.setSoTimeout();
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
} X509Certificate[] chain = tm.chain;
if (chain == null) {
System.out.println("Could not obtain server certificate chain");
return;
} BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in)); System.out.println();
System.out.println("Server sent " + chain.length + " certificate(s):");
System.out.println();
MessageDigest sha1 = MessageDigest.getInstance("SHA1");
MessageDigest md5 = MessageDigest.getInstance("MD5");
for (int i = ; i < chain.length; i++) {
X509Certificate cert = chain[i];
System.out.println
(" " + (i + ) + " Subject " + cert.getSubjectDN());
System.out.println(" Issuer " + cert.getIssuerDN());
sha1.update(cert.getEncoded());
System.out.println(" sha1 " + toHexString(sha1.digest()));
md5.update(cert.getEncoded());
System.out.println(" md5 " + toHexString(md5.digest()));
System.out.println();
} System.out.println("Enter certificate to add to trusted keystore or 'q' to quit: [1]");
String line = reader.readLine().trim();
int k;
try {
k = (line.length() == ) ? : Integer.parseInt(line) - ;
} catch (NumberFormatException e) {
System.out.println("KeyStore not changed");
return;
} X509Certificate cert = chain[k];
String alias = host + "-" + (k + );
ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream("jssecacerts");
ks.store(out, passphrase);
out.close(); System.out.println();
System.out.println(cert);
System.out.println();
System.out.println
("Added certificate to keystore 'jssecacerts' using alias '"
+ alias + "'");
} private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray(); private static String toHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder(bytes.length * );
for (int b : bytes) {
b &= 0xff;
sb.append(HEXDIGITS[b >> ]);
sb.append(HEXDIGITS[b & ]);
sb.append(' ');
}
return sb.toString();
} private static class SavingTrustManager implements X509TrustManager { private final X509TrustManager tm;
private X509Certificate[] chain; SavingTrustManager(X509TrustManager tm) {
this.tm = tm;
} public X509Certificate[] getAcceptedIssuers() {
throw new UnsupportedOperationException();
} public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
throw new UnsupportedOperationException();
} public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
this.chain = chain;
tm.checkServerTrusted(chain, authType);
}
} }

编译:javac InstallCert.java 
运行:java InstallCert ecc.fedora.redhat.com

C:\Program Files\Java\jdk1.8.0_74\jre\lib\security

解决 sun.security.validator.ValidatorException: PKIX path building failed的更多相关文章

  1. 抓取https网页时,报错sun.security.validator.ValidatorException: PKIX path building failed 解决办法

    抓取https网页时,报错sun.security.validator.ValidatorException: PKIX path building failed 解决办法 原因是https证书问题, ...

  2. 异常信息:javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed

    上周五遇到一个问题,工程本地编译运行正常,打包本地tomcat运行也正常.部署到测试环境报错: 2017-05-05 09:38:11.645 ERROR [HttpPoolClientsUtil.j ...

  3. Maven:sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    还是记录使用 maven 时遇到的问题. 一.maven报错 maven package 进行打包时出现了以下报错: Non-resolvable parent POM for com.wpbxin: ...

  4. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed

    1.使用HttpClient4.3 调用https出现如下错误: javax.net.ssl.SSLHandshakeException: sun.security.validator.Validat ...

  5. javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certificatio

    场景:Java调用PHP接口,代码部署在服务器上后,调用报错,显示PHP服务器那边证书我这边服务器不信任(我猜的). 异常信息: 2019-08-06 14:00:09,102 [http-nio-4 ...

  6. mvn 编译报错mavn sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested targ

    mavn 编译报错: mavn sun.security.validator.ValidatorException: PKIX path building failed: sun.security.p ...

  7. ES访问遇到sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    cmd命令cd到jre/bin目录下 输入命令keytool -import -alias 别名 -keystore cacerts -file ‪C://certs//elasticsearch// ...

  8. sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

    httpclient-4.5.jar 定时发送http包,忽然有一天报错,http证书变更引起的. 之前的代码 try { CloseableHttpClient httpClient = build ...

  9. javax.net.ssl.sslhandshakeException:sun.security.validator.validatorException:PKIX path buildind failed

    前段时间开发的一个需求,需要通过图片URL获取图片的base64编码,测试的时候使用的是百度图片的url,测试没有问题,但是发布后测试时报如下错: javax.net.ssl.sslhandshake ...

随机推荐

  1. mysql hql异常

    org.springframework.dao.InvalidDataAccessResourceUsageException:  could not execute query; nested ex ...

  2. HDU 5159 Card

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5159 题解: 考虑没一个数的贡献,一个数一次都不出现的次数是(x-1)^b,而总的排列次数是x^b, ...

  3. HDU 5191 Building Blocks

    题目链接: hdu:http://acm.hdu.edu.cn/showproblem.php?pid=5191 bc(中文):http://bestcoder.hdu.edu.cn/contests ...

  4. 对mysql联合索引中的字段进行合理排序

    在MySQL的where条件中,有时会用到很多的条件,通常为了加快速度会把这些字段放到联合索引中,可以更快的提高搜索速度: 但是对联合索引中字段顺序的合理排序,便更能提高速度 例子:select * ...

  5. 第202天:js---原型与原型链终极详解

    一. 普通对象与函数对象 JavaScript 中,万物皆对象!但对象也是有区别的.分为普通对象和函数对象,Object .Function 是 JS 自带的函数对象.下面举例说明 var o1 = ...

  6. 【bzoj4011】[HNOI2015]落忆枫音 容斥原理+拓扑排序+dp

    题目描述 给你一张 $n$ 个点 $m$ 条边的DAG,$1$ 号节点没有入边.再向这个DAG中加入边 $x\to y$ ,求形成的新图中以 $1$ 为根的外向树形图数目模 $10^9+7$ . 输入 ...

  7. Java 读取Excel2007 jar包冲突的问题(org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException)

    1.jar包冲突报错问题 2.使用的jar包,以及重复jar包 3.删除重复jar包

  8. C++解析(23):多态与C++对象模型

    0.目录 1.多态 2.C++对象模型 2.1 使用C语言实现封装 3.继承对象模型 4.多态对象模型 4.1 使用C语言实现多态 5.小结 1.多态 面向对象中期望的行为: 根据实际的对象类型判断如 ...

  9. Matrix Walk CodeForces - 954C

    题意: 就是给出一连串的数字 这些数字是从第一个数字依次走过的 emm..就是这样..  然后让你判断这个矩阵是否存在  如果存在输出行和列的数量  其中行..开到最大就好了...主要是判断列 在输入 ...

  10. java学习1-环境搭建

    1.材料准备 2.配置文档 3.验证java是否安装成功 打开cmd-->  java -version 提示以下即成功