使用Java从https获取图像 [英] Getting images from https with Java
问题描述
有没有办法从带有Java的https网址获取图片?
Is there a way to get images from a https url with Java?
到目前为止我正在尝试:
What I am trying so far:
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
我该怎么办呢?我在那个网址上有超过6k的图像,我必须提取。
How can I go through that? I have more than 6k images on that url that I have to fetch.
推荐答案
有两个问题。您可以使用浏览器访问该网站,并查看错误。
There are two problems. You can use your browser to access the site, and see the errors.
-
服务器证书是自签名的,不受信任的通过Java。您可以将其添加到信任存储区。
The server certificate is self-signed, not trusted by Java. you can add it to the trust store.
服务器证书与主机名ns6.host.md不匹配,您需要 HostnameVerifier
忽略它。
The server certificate does not match the host name "ns6.host.md", and you need a HostnameVerifier
that ignores it.
另一个答案说同样的事情,它提供了代码,不幸的是使用了一些私有API。
The other answer says the same thing, and it provides code, which unfortunately uses some private APIs.
如果有人感兴趣的话,如何解决它在bayou HttpClient中的示例:
https://gist.github.com/zhong-j-yu/22af353e2c5a5aed5857
Example how to solve it in bayou HttpClient, if anyone is interested: 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);
}
这篇关于使用Java从https获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!