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));
But, I am getting:
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
How can I go through that? I have more than 6k images on that url that I have to fetch.
Best How To :
There are two problems. You can use your browser to access the site, and see the errors.
The server certificate is self-signed, not trusted by Java. you can add it to the trust store.
The server certificate does not match the host name "ns6.host.md", and you need a
HostnameVerifier that ignores it.
The other answer says the same thing, and it provides code, which unfortunately uses some private APIs.
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))
// 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.