Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
192 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...