JAVA: What's the fastest and best way to get a response code from HTTPS URL?

2.6k Views Asked by At
    private int getResponse(String url) throws Exception {

    try {
       URL check = new URL(url);
       HttpsURLConnection connection = (HttpsURLConnection)check.openConnection();
       connection.setRequestMethod("GET");
       connection.setConnectTimeout(5000);
       connection.connect();

       return(connection.getResponseCode());

    } catch (java.net.SocketTimeoutException e) {
           return getResponse(url);
    }

}

Is there a faster way to get the response code from a URL than HttpsURLConnection?

I tried HeadMethod from the HTTP Client Commons but that's not that much faster.

Thanks in advance

1

There are 1 best solutions below

0
On

I strongly suspect that differences will be absolutely minimal, when compared to normal internet delays and the network stack that Java itself is using (provided by the underlying OS).

While making 1 request will incur in roughly the same overhead regardless of library (as long as it is not completely broken; both Apache Commons and JDK are ok), if you are going to make multiple requests, there are several things that will dramatically improve performance:

  • If you need to complete several requests as soon as possible, and do not need each one to complete before you can start others, then go parallel. A useful pointer may be https://github.com/AsyncHttpClient/async-http-client (part of Project Grizzly; uses NIO for non-blocking, highly scalable communication)
  • If you will perform additional requests from the same site, then you will see a dramatic performance improvement (> 2x) if you use the keep-alive header and reuse the same connection for several requests. This is due to the high setup costs of HTTPS connections. More information at HTTP vs HTTPS performance (and a nice diagram here). First-time HTTPS requests need 2 round-trips to negotiate encryption before any data is exchanged; further requests can avoid the handshake.