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?