Organizational Research By

Surprising Reserch Topic

preferred java way to ping a http url for availability


preferred java way to ping a http url for availability  using -'java,http,url,ping'

I need a monitor class that regularly checks whether a given HTTP URL is available. I can take care of the "regularly" part using the Spring TaskExecutor abstraction, so that's not the topic here. The Question is: What is the preferred way to ping a URL in java?

Here is my current code as a starting point:

try{
    final URLConnection connection = new URL(url).openConnection();
    connection.connect();
    LOG.info("Service " + url + " available, yeah!");
    available = true;
} catch(final MalformedURLException e){
    throw new IllegalStateException("Bad URL: " + url, e);
} catch(final IOException e){
    LOG.info("Service " + url + " unavailable, oh no!", e);
    available = false;
}



Is this any good at all (will it do what I want?)
Do I have to somehow close the connection?
I suppose this is a GET request. Is there a way to send HEAD instead?

    

asked Sep 30, 2015 by rajeshujade
0 votes
12 views



Related Hot Questions

6 Answers

0 votes

Is this any good at all (will it do what I want?)

You can do so. Another feasible way is using java.net.Socket.

Socket socket = null;
boolean reachable = false;
try {
    socket = new Socket(hostnameOrIP, 80);
    reachable = true;
} finally {            
    if (socket != null) try { socket.close(); } catch(IOException e) {}
}

There's also the InetAddress#isReachable():

boolean reachable = InetAddress.getByName(hostname).isReachable();

This however doesn't explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.


Do I have to somehow close the connection?

No, you don't explicitly need. It's handled and pooled under the hoods.


I suppose this is a GET request. Is there a way to send HEAD instead?

You can cast the obtained URLConnection to HttpURLConnection and then use setRequestMethod() to set the request method. However, you need to take into account that some poor webapps or homegrown servers may return HTTP 405 error for a HEAD (i.e. not available, not implemented, not allowed) while a GET works perfectly fine. But, those are pretty rare cases.


Update as per the comments: connecting a host only informs if the host is available, not if the content is available. You seem to be more interested in the content since it can as good happen that a webserver has started without problems, but the webapp failed to deploy during server's start. This will however usually not cause the entire server to go down. So you'd like to determine the HTTP response code.

HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("HEAD");
int responseCode = connection.getResponseCode();
if (responseCode != 200) {
    // Not OK.
}

// < 100 is undetermined.
// 1nn is informal (shouldn't happen on a GET/HEAD)
// 2nn is success
// 3nn is redirect
// 4nn is client error
// 5nn is server error

For more detail about response status codes see RFC 2616 section 10. Calling connect() is by the way not needed if you're determining the response data. It will implicitly connect.

For future reference, here's a complete example in flavor of an utility method, also taking account with timeouts:

/**
 * Pings a HTTP URL. This effectively sends a HEAD request and returns true if the response code is in 
 * the 200-399 range.
 * @param url The HTTP URL to be pinged.
 * @param timeout The timeout in millis for both the connection timeout and the response read timeout. Note that
 * the total timeout is effectively two times the given timeout.
 * @return true if the given HTTP URL has returned response code 200-399 on a HEAD request within the
 * given timeout, otherwise false.
 */
public static boolean ping(String url, int timeout) {
    // Otherwise an exception may be thrown on invalid SSL certificates:
    url = url.replaceFirst("^https", "http");

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        connection.setRequestMethod("HEAD");
        int responseCode = connection.getResponseCode();
        return (200 <= responseCode && responseCode <= 399);
    } catch (IOException exception) {
        return false;
    }
}
answered Sep 30, 2015 by sanjaypal1983
0 votes

Instead of using URLConnection use HttpURLConnection by calling openConnection() on your URL object.

Then use getResponseCode() will give you the HTTP response once you've read from the connection.

here is code:

    HttpURLConnection connection = null;
    try {
        URL u = new URL("http://www.google.com/");
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("HEAD");
        int code = connection.getResponseCode();
        System.out.println("" + code);
        // You can determine on HTTP return code received. 200 is success.
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

Also check similar question questions/1378199/how-to-check-if-a-url-exists-or-returns-404-with-java

Hope this helps.

answered Sep 30, 2015 by mca.agarwal
0 votes

You could also use HttpURLConnection, which allows you to set the request method (to HEAD for example). Here's an example that shows how to send a request, read the response, and disconnect.

answered Sep 30, 2015 by deepak07.s
0 votes

Consider using the Restlet framework, which has great semantics for this sort of thing. It's powerful and flexible.

The code could be as simple as:

Client client = new Client(Protocol.HTTP);
Response response = client.get(url);
if (response.getStatus().isError()) {
    // uh oh!
}
answered Sep 30, 2015 by rajeshujade
0 votes

The following code performs a HEAD request to check whether the website is available or not.

public static boolean isReachable(String targetUrl) throws IOException
{
    HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
            targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");

    try
    {
        int responseCode = httpUrlConnection.getResponseCode();

        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (UnknownHostException noInternetConnection)
    {
        return false;
    }
}
answered Sep 30, 2015 by vimaldas2005
0 votes

wrt 2.: you'd better do close it. However, it may depend on the particular implementation of URLConnection which is used. I have just finished tracking down a resource leak in our system just because of that. An app generated lots of hanging connections (according to lsof; we're running it on JDK1.6) and the reason was we have used exactly the piece of code you have shown. TCP Connections were not closed neither e.g. returned to pool etc. - they were left in ESTABILISHED state. In this case, the proper scenario is the one shown by YoK - cast it to (HttpURLConnection) and invoke .disconnect().

answered Sep 30, 2015 by sanjaypal1983

...