views:

1475

answers:

3

Using Java, how can I test that a URL is contactable, and returns a valid response?

http://stackoverflow.com/about
+2  A: 

HttpUnit

Chris Jester-Young
+4  A: 

The solution as a unit test:

public void testURL() throws Exception {
    String strUrl = "http://stackoverflow.com/about";

    try {
        URL url = new URL(strUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        System.err.println("Error creating HTTP connection");
        e.printStackTrace();
        throw e;
    }
}
brass-kazoo
@David: No, often people ask questions they already know the answer for, just to provide more useful content for SO.
Chris Jester-Young
Far enough, apologize for the comment in that case. And thanks for sharing the solution then...
David Santamaria
+1  A: 

Since java 5 if i recall, the InetAdress class contains a method called isReachable(); so you can use it to make a ping implementation in java. You can also specify a timeout for this method. This is just another alternative to the unit test method posted above, which is probably more efficient.

John T
isReachable only tests that you can reach the site, not that the site is actually running (e.g., returning 200 rather than 500 or the like).
Chris Jester-Young
Also, unit tests are required more to be thorough, than efficient. :-P
Chris Jester-Young