22

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

http://stackoverflow.com/about
brasskazoo
  • 76,030
  • 23
  • 64
  • 76

4 Answers4

47

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;
    }
}
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
brasskazoo
  • 76,030
  • 23
  • 64
  • 76
  • @David: No, often people ask questions they already know the answer for, just to provide more useful content for SO. – C. K. Young Nov 12 '08 at 23:58
  • Far enough, apologize for the comment in that case. And thanks for sharing the solution then... – David Santamaria Nov 13 '08 at 00:01
  • @brass-kazoo I got connection refused exception :( – Xitrum Oct 27 '12 at 11:35
  • 1
    Isn't it also necessary to call `urlCon.disconnect()` in a `finally` block? And maybe also completely consume the `InputStream`? – Enwired Oct 29 '14 at 23:23
  • 5
    If you use it on a comuter available on your network but with no webserver running, this method will hang. You need to use setConnectTimeout and/or setReadTimeout on the HttpURLConnection. – Tim Autin Jan 13 '15 at 14:59
7

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
  • 23,735
  • 11
  • 56
  • 82
0
System.out.println(new InetSocketAddress("http://stackoverflow.com/about", 80).isUnresolved());

delivers false if page is reachable, which is a precondition.

In order to cover initial question completely, you need to implement a http get or post.

Sam Ginrich
  • 661
  • 6
  • 7
-12
import org.apache.commons.validator.UrlValidator;

public class ValidateUrlExample {

    public static void main(String[] args) {

        UrlValidator urlValidator = new UrlValidator();

        //valid URL
        if (urlValidator.isValid("http://www.mkyong.com")) {
            System.out.println("url is valid");
        } else {
            System.out.println("url is invalid");
        }

        //invalid URL
        if (urlValidator.isValid("http://invalidURL^$&%$&^")) {
            System.out.println("url is valid");
        } else {
            System.out.println("url is invalid");
        }
    }
}

Output:

url is valid
url is invalid

source : http://www.mkyong.com/java/how-to-validate-url-in-java/

DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Charif
  • 1
  • 1