Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (4k points)

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;

}

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

1 Answer

0 votes
by (46k points)

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();

        }

    }

Hope this helps.

Related questions

0 votes
1 answer
asked Nov 24, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
asked Sep 30, 2019 in Java by Anvi (10.2k points)

Browse Categories

...