首页 > 解决方案 > 在 Java 中下载图像时忽略证书

问题描述

我正在使用下面的代码下载只能通过 HTTPS 获得的图像。证书已过期,所以如果我想下载图片,我必须手动点击浏览器中的忽略证书错误。我怎样才能在我的代码中做同样的事情?

URL website = new URL("https://domain/image.jpg");    
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream("C:\\temp\\image.jpg");
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();

这是我使用此代码得到的异常:

Exception in thread "main" javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
    at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
    at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    at DownloadImage.main(DownloadImage.java:17)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
    at sun.security.ssl.InputRecord.read(Unknown Source)

标签: javaurl

解决方案


推荐阅读