使用Java从https获取图像


问题内容

有没有办法使用Java从https网址获取图像?

到目前为止,我正在尝试:

URL url = new URL("https://ns6.host.md:8443/sitepreview/http/zugo.md/media/images/thumb/23812__yu400x250.jpg");

System.out.println("Image: " + ImageIO.read(url));

但是,我得到:

Exception in thread "main" javax.imageio.IIOException: Can't get input stream from URL!
Caused by: javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No 
Caused by: java.security.cert.CertificateException: No name matching ns6.host.md found

我该如何处理?我必须提取该URL上的6k张图像以上。


问题答案:

有两个问题。您可以使用浏览器访问该网站,并查看错误。

  1. 服务器证书是自签名的,不受Java信任。您可以将其添加到信任库。

  2. 服务器证书与主机名“ ns6.host.md”不匹配,因此您需要一个HostnameVerifier忽略它的证书。

另一个答案也是如此,它提供了代码,不幸的是,它们使用了一些私有API。

如果有兴趣的话,如何在bayou HttpClient中解决该示例:https : //gist.github.com/zhong-j-
yu/22af353e2c5a5aed5857

public static void main(String[] args) throws Exception
{
    HttpClient client = new HttpClientConf()
        .sslContext(new SslConf().trustAll().createContext()) // trust self-signed certs
        .sslEngineConf(engine -> disableHostNameVerification(engine))
        .trafficDump(System.out::print)
        .newClient();
    // typically, app creates one client and use it for all requests

    String url = "https://ns6.host.md:8443/sitepreview/http/zugo.md/media/images/thumb/23812__yu400x250.jpg";
    HttpResponse response = client.doGet(url).sync();
    ByteBuffer bb = response.bodyBytes(Integer.MAX_VALUE).sync();

    InputStream is = new ByteArrayInputStream(bb.array(), bb.arrayOffset()+bb.position(), bb.remaining());
    BufferedImage image = ImageIO.read(is);

}

static void disableHostNameVerification(SSLEngine engine)
{
    SSLParameters sslParameters = engine.getSSLParameters();
    {
        // by default, it's set to "HTTPS", and the server certificate must match the request host.
        // disable it for this example, since the server certificate is ill constructed.
        sslParameters.setEndpointIdentificationAlgorithm(null);
    }
    engine.setSSLParameters(sslParameters);
}