Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programmatically test an HTTP connection?

Tags:

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

http://stackoverflow.com/about 
like image 786
brasskazoo Avatar asked Nov 12 '08 23:11

brasskazoo


People also ask

What is HttpURLConnection in Java?

public abstract class HttpURLConnection extends URLConnection. A URLConnection with support for HTTP-specific features. See the spec for details. Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances.


1 Answers

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;     } } 
like image 116
brasskazoo Avatar answered Oct 18 '22 14:10

brasskazoo