简体   繁体   中英

how to check url connection status in java

I am executing the get request in java using "URLConnection". I am sending the get requests to different Ip addresses in order to generate the alarm.If the url is valid it made the connection and read the data return from the url, but it doesnt return any thing if the connection is unsuccessful. I need to know is there any isconnect method in urlconnection because i need to set a flags for my program and I couldn't find any way to determine the unsuccessful connection, I am using the following code: URL url = new URL(address);

         URLConnection conn = url.openConnection();
         conn.setConnectTimeout(20);
         //bool flag=conn.isconnect()


        BufferedReader br = new BufferedReader(new 
        InputStreamReader(conn.getInputStream()));              
       System.out.println("connected"); 

      while ((line = br.readLine()) != null)
      {
        result += line;

      }
      //if (flag){triggered the ip}
      //if (!flag){not triggered}

I need to execute the commented if conditions, but I am struggling on it because the program doesnt reach after the "bufferedReader br" statement if the ip is invalid or if it is not present.

url.openConnection, conn.getInputStream will throw up exceptions when the connection cannot be established.

The only problem is if your server will accept the conneciton but will not send enything (cause it hangs, the code on server side has a bug). For that reason you have to call setConnectTimeout to get an exception when it happens.

Appology you already set the timeout. The exception handling should do the job.

try {
    URLConnection conn = url.openConnection();
    conn.setConnectTimeout(20);
    conn.setReadTimeout(...)

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("connected");

    while ((line = br.readLine()) != null) {
        result += line;
    }
} catch (IOException e) {
    ... deal with wrong address, timeout and etc
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM