how to check url connection status in java

五迷三道 提交于 2019-12-12 06:56:07

问题


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.


回答1:


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
}


来源:https://stackoverflow.com/questions/28701641/how-to-check-url-connection-status-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!