How can I programmatically add a self signed certificate to issue HTTPS requests from Java code?

The following code snippet is to get a JSON response from an HTTP URL:

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 sslhandshaking exception because I didn't add a self - signed authentication exception to my code I did this in c# but not in Java What steps should I take? Need your advice:)

Thank you in advance

Solution

You can configure the httpsurlconnection socket factory to accept all certificates without any authentication:

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

You only need to call this code once when the application starts Use URL All HTTPS connections opened by openconnection() will use this socket factory Another solution is to add this code to the createsslsocket () method body

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>