Received fatal alert: bad_certificate

萝らか妹 提交于 2019-12-02 20:59:06

You need to add the root cert to the keystore as well.

Provided that the server certificate is signed and valid, you only need to open the connection as usual:

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL google = new URL("https://www.google.com/");
        URLConnection yc = google.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                    yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
    }
}

Note that the URL has the HTTPS schema to indicate the use of SSL.

If the server's certificate is signed but you are accessing using a different IP address/domain name than the one in the certificate, you can bypass hostname verification with this:

HostnameVerifier hv = new HostnameVerifier() {
    public boolean verify(String urlHostName,SSLSession session) {
        return true;
    }
};

HttpsURLConnection.setDefaultHostnameVerifier(hv);

If the certificate is not signed then you need to add it to the keystore used by the JVM (useful commands).

I got this error when I removed these 2 lines. If you know your keystore has the right certs, make sure your code is looking at the right keystore.

System.setProperty("javax.net.ssl.keyStore", <keystorePath>));
System.setProperty("javax.net.ssl.keyStorePassword",<keystorePassword>));

I also needed this VM argument: -Djavax.net.ssl.trustStore=/app/certs/keystore.jk See here for more details: https://stackoverflow.com/a/34311797/1308453

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!