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
GETrequest. Is there a way to sendHEADinstead?
You can do so. Another feasible way is using
java.net.Socket.There’s also the
InetAddress#isReachable():This however doesn’t explicitly test port 80. You risk to get false negatives due to a Firewall blocking other ports.
No, you don’t explicitly need. It’s handled and pooled under the hoods.
You can cast the obtained
URLConnectiontoHttpURLConnectionand then usesetRequestMethod()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. Using GET is more reliable in case you intend to verify links/resources not domains/hosts.Indeed, connecting a host only informs if the host is available, not if the content is available. 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. You can determine that by checking if the HTTP response code is 200.
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: