今天用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. Log4Net的使用研究(一)

    等待研究中………… 20160421 标题:C#使用Log4Net记录日志   文章地址: http://www.cnblogs.com/wangsaiming/archive/2013/01/11/ ...

  2. C#控制台应用程序

    使用C#创建控制台应用程序的基本步骤: (1)创建项目: (2)编辑C#源代码: (3)编译运行: 例题:在控制台输出“Hello world!”. 第一步:文件→新建→项目:选择“项目类型”为Vis ...

  3. phaser2 微信小游戏入手

    phaser2小游戏基本没什么什么问题,可以下常开发游戏.如果遇到什么问题, 可以提出来共同讨论. 下面来个例子 import './lib/weapp-adapter'; import Phaser ...

  4. delphi完美经典--第十八章

    第18章数据感知组件 一.TDBText组件 用来以只读.一次一条记录的方式,显示DataSet中的某一字段值.因同样继承自TCustomLabel,TDBText组件除了数据感知功能外,与标准组件T ...

  5. delphi self 的使用

    delphi之self 在使用delphi的对象技术的时候,经常会看到一个词汇:self,它到底指的是什么呢? 我们还要从对象与类的关系谈起. 类是对将要创建的对象的性质的描述,是一种文档.这很重要: ...

  6. SpringMVC Ajax两种传参方式

    1.采用@RequestParam或Request对象获取参数的方法 注:contentType必须指定为:application/x-www-form-urlencoded @ResponseBod ...

  7. 第200天:js---常用string原型扩展

    一.常用string原型扩展 1.在字符串末尾追加字符串 /** 在字符串末尾追加字符串 **/ String.prototype.append = function (str) { return t ...

  8. Argus UVALive - 3135(优先队列 水题一道)

    有一系列的事件,它每Period秒钟就会产生编号为qNum的事件,你的任务是模拟出前k个事件,如果多个事件同时发生,先处理qNum小的事件 今天再看看数据结构.. #include <iostr ...

  9. 基于ORM实现用户登录

    1. 与数据库中的数据进行比较,检验用户名和密码是否正确. 2. 拿到的是QuerySet类型,类似于一个列表.验证成功/失败,返回到不同的页面. u = request.POST.get('user ...

  10. NHibernate 设置主键不自增长

    1.Model 配置 [PrimaryKey(PrimaryKeyType.Assigned,"ID")] 2.使用时要手动赋值