I need a monitor class that regularly checks whether a given the 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's the preferred-to-ping a URL in Java?
Here's my current code as a starting point:
Packageorg.javalobby.tnt.net;Importjava.io.IOException;Importjava.net.MalformedURLException;ImportJava.net.URL;Importjava.net.URLConnection; Public classDnstest { Public Static voidMain (string[] args) {String URL= "Http://www.baidu.com"; Try{ FinalURLConnection connection =Newurl (url). OpenConnection (); Connection.connect (); System.out.println ("Service" + URL + "available, yeah!"); } Catch(Finalmalformedurlexception e) { Throw NewIllegalStateException ("Bad URL:" +URL, e); } Catch(FinalIOException E) {System.out.println ("Service" + URL + "unavailable, OH no! " +e); } }}
- Is the good at all (would it do I want?)
- Do I has to somehow close the connection?
- I Suppose this is a GET request. Is there a-to send HEAD instead?
Is the good at all (would it do I want?)
You can do so. Another feasible is using java.net.Socket .
url = "Www.baidu.com"; Socket Socket=NULL; Booleanreachable =false; Try{Socket=NewSocket (URL, 80); Reachable=true; System.out.println ("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 has 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-to send HEAD instead?
You can cast the obtained to and then use the to URLConnection HttpURLConnection set the setRequestMethod() request method. However, you need-to-take-into account that some poor WebApps or homegrown servers could return HTTP 405 error for a HEAD (i . E. Not available, not implemented, not allowed) while a GET works perfectly fine. But, those is pretty rare cases.
Update as per the comments:connecting a host only informs if the host was available, not if the content is Availa ble. You seem to is more interested in the content since it can as good happen that a webserver have started without problems, b UT the webapp failed to deploy during server ' s start. This would however usually not cause the entire server to go down. So you ' d like to determine the HTTP response code.
url = "Http://www.baidu.com"; HttpURLConnection Connection= (httpurlconnection)Newurl (url). OpenConnection (); Connection.setrequestmethod ("HEAD"); intResponsecode =Connection.getresponsecode (); if(Responsecode! = 200) { //Not OK.System.out.println ("Not OK"); } //< 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 on response status codes see RFC 2616 section 10. Calling is by the the connect() -the-needed if you ' re determining the response data. It'll implicitly Connect.
For the reference, here's a complete example in flavor of a utility method, also taking account with timeouts:
/*** Pings a HTTP URL. This effectively sends a HEAD request and returns <code>true</code> if the response code was in * the 200-399 Range. * @paramURL The HTTP URL to is pinged. *@paramtimeout The timeout in Millis for both the connection timeout and the response read timeout. Note that * The total timeout is effectively and the given timeout. * @return<code>true</code> If the given HTTP URL has returned response code 200-399 on a HEAD request within the * Given timeout, otherwise <code>false</code>. */ Public Static BooleanPing (String URL,intTimeout) {URL= Url.replacefirst ("https", "http");//Otherwise An exception is thrown on invalid SSL certificates. Try{httpurlconnection Connection= (httpurlconnection)Newurl (url). OpenConnection (); Connection.setconnecttimeout (timeout); Connection.setreadtimeout (timeout); Connection.setrequestmethod ("HEAD"); intResponsecode =Connection.getresponsecode (); return(<= responsecode && responsecode <= 399); } Catch(IOException exception) {return false; }}
Preferred Java-to-ping a HTTP Url for availability