How to check whether the connection is established or not in java?

1.7k views Asked by At

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 ?

3

There are 3 answers

2
Antoniossss On

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. BTW getInputStream is calling connect() behind the scenes if you haven't do so before that call.

Refere to javadocs for more informations.

1
Srinivasu On

By ping we can check the system status

String command = "ping -c 3 " + IP;
Process p = Runtime.getRuntime().exec(command);
0
user207421 On

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.

You have checked. You got the IOException. That told you. If you want to get it earlier in the piece, call connect() or getResponseCode(). If getResponseCode() doesn't throw an IOException and returns 200, read the input stream.