简体   繁体   中英

Monitor a HTTPS connection with URL class (Java)

I would like to monitor a simple url . But when its a https server I get a handshake exception . Its possible to verify state of a https url the way browser use to connect? (without having a local certificate). I don't know how browsers do to get content from a https url but I would like to make it the same way. Without need to store a specific certificate for each server. The https being monitored should be anyone.

try {
    URL u = new URL(row.getUrl());
    String protocol = u.getProtocol();
    if(protocol.equals("https")) {
        HttpsURLConnection hc = (HttpsURLConnection)u.openConnection();
        System.out.println("Response Code: " + hc.getResponseCode());
        hc.disconnect();
    }
    if(protocol.equals("http")) {
    u.openConnection();
    u.getContent();
    }
    System.out.println("url is up.");
} catch (Exception e) {
    (...)
}

If you really don't care about the validity of the server's certificate, then you want to set an SSLContext that has a TrustManager that doesn't check anything. Then you need to use that to set the default SSLSocketFactory into the HttpsURLConnection , so that the trust manager is used when you use the URL . Here's an example:

TrustManager[] trustEverything = new TrustManager[] {
    new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() { return null; }
        public void checkClientTrusted(X509Certificate[] certs, String authType) { }
        public void checkServerTrusted(X509Certificate[] certs, String authType) { }
    }
};

SSLContext sslctx = SSLContext.getInstance("SSL");
sslctx.init(null, trustEverything, null);

HttpsURLConnection.setDefaultSSLSocketFactory(sslctx.getSocketFactory());

A full example using this technique can be found here .

As @erickson points out, this means that you can't tell if you're really talking to the server you're concerned about. An even better solution is to update your Trust store to include the self-signed certificate of the server you're talking to, instead of ignoring all checks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM