How to programmatically add a self-signed certificate to create an HTTPS request from Java code?

The following code snippet should receive a response JSonfrom the URL HTTP:

private static void getJson(String location) {
    try {
        try {
            createSSLSocket();
            URL url = new URL(
                    "https://abc.com/key/one");
            HttpURLConnection conn = (HttpURLConnection) url
                    .openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + conn.getResponseCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();

        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

But it throws an exception SSLHandshakingbecause I did not add a self-signed certification exception to the code. I did this in C#, but not in java. What steps should I follow? You need your suggestion :)

Thanks in advance.

+3
source share
2 answers

You can configure the HttpsURLConnectionfactory socket to accept the whole certificate without any validation:

private class TrustAll implements X509TrustManager
{
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
    {
    }

    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException
    {
    }

    public X509Certificate[] getAcceptedIssuers()
    {
        return new X509Certificate[0];
    }
}

SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { new TrustAll() }, null);
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

UPDATE

. HTTPS, URL.openConnection(), factory. createSSLSocket().

+3

, truststore java javax.net.ssl.trustStore . openConnection , , .

, keytool, JDK JAVA_HOME/bin.

keytool -import -file yourcert.cert -alias abc -keystore truststore.jks

, , . truststore.jks. Java, -Djavax.net.ssl.trustStore=/path/truststore.jks System.setProperty

System.setProperty("javax.net.ssl.trustStore", "/path/truststore.jks");

ssl, Java, .

+4

Source: https://habr.com/ru/post/1526908/


All Articles