如何在Java中检查URL连接状态 [英] how to check url connection status in java

查看:274
本文介绍了如何在Java中检查URL连接状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用"URLConnection"在Java中执行get请求.我将get请求发送到不同的Ip地址以生成警报.如果url有效,则建立连接并读取从url返回的数据,但如果连接失败则不返回任何内容.我需要知道urlconnection中是否有任何isconnect方法,因为我需要为我的程序设置一个标志,并且找不到任何方法来确定不成功的连接,我正在使用以下代码: 网址url =新网址(地址);

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}

我需要执行if条件注释,但是我正在努力解决这个问题,因为如果ip无效或不存在,则该程序在"bufferedReader br"语句之后无法到达.

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将引发异常.

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

唯一的问题是服务器是否接受连接但不发送任何信息(因为它挂起,服务器端的代码有错误). 因此,您必须调用setConnectTimeout才能在发生异常时获取异常.

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.异常处理可以完成这项工作.

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
}

这篇关于如何在Java中检查URL连接状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆