How can I programmatically test an HTTP connection?
Solution 1
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;
}
}
Solution 2
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.
Related videos on Youtube
brasskazoo
I am a Software and Cloud Solutions Engineer with a passion for building quality and automation into the development, testing and deployment lifecycles. Currently working with a large AWS hybrid-cloud integration project, including VPC architecting and solution design, serverless applications and shifting applications to EC2. Primarily I work with terraform, node.js, react and java, with side projects currently in react-native and GraphQL for cross-platform mobile applications. Agile, DevOps culture, Code Quality and Continuous Integration are cornerstones of my development efforts.
Updated on July 09, 2022Comments
-
brasskazoo almost 2 years
Using Java, how can I test that a URL is contactable, and returns a valid response?
http://stackoverflow.com/about
-
C. K. Young over 15 years@David: No, often people ask questions they already know the answer for, just to provide more useful content for SO.
-
C. K. Young over 15 yearsisReachable 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).
-
C. K. Young over 15 yearsAlso, unit tests are required more to be thorough, than efficient. :-P
-
Charlie over 15 yearsFar enough, apologize for the comment in that case. And thanks for sharing the solution then...
-
Xitrum over 11 years@brass-kazoo I got connection refused exception :(
-
Daniel Kamil Kozar over 10 years-1. This does not answer the question at all : the code you posted only checks if the URL is valid, not if the host under that URL is reachable or gives a given response.
-
Katianie over 9 yearsThis is a misleading answer -1 for that.
-
Enwired over 9 yearsIsn't it also necessary to call
urlCon.disconnect()
in afinally
block? And maybe also completely consume theInputStream
? -
Tim Autin over 9 yearsIf 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.