I want to establish a connection using a url but i am getting IO exception because my server is not up . i want to check whether my connection is established or not how can i acheive this in java. here is my code
URLConnection connection = new URL(configurationManagement.getValue(url)).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.3) Gecko/20100401"); // Do as if you'rusing Firefox 3.6.3
InputStream response = connection.getInputStream();
Can anybody help ?
You are doing it right now (not straightworward). If you will be able to read from input stream (read some data, or block waiting for input) will mean that connection is up and running. Exception will be thrown otherwise.
You can always call
URLConnection#connect()
to explicitly connect to provided resource, and again if exception is not thrown, you got the connection. BTWgetInputStream
is callingconnect()
behind the scenes if you haven't do so before that call.Refere to javadocs for more informations.