2013-03-28 58 views
1

系统的互联网连接我写了一个方法,这将有助于我们发现使用代理系统是否与网上有如下连接,检查使用Java

try { 

    System.out.println("Checking internet connection availability....."); 
    URL u = new URL("http://www.google.com/"); 
    HttpURLConnection uc = (HttpURLConnection) u.openConnection(); 
    uc.setReadTimeout(1);//I have tried this without timeout and with it too. But it didnt work 
    System.out.println(uc.getResponseCode()); 
} catch (Exception ex) { 
    System.out.println("Unable to connect to internet without proxy....."); 
    System.out.println("Checking for any proxy settings from the PC"); 
    System.setProperty("java.net.useSystemProxies", "true"); 
    try { 
     System.setProperty("java.net.useSystemProxies", "true"); 
     URL u = new URL("http://www.google.com/"); 
     HttpURLConnection uc = (HttpURLConnection) u.openConnection(); 
     System.out.println(uc.getResponseCode()); 
     System.out.println("Internet connection available"); 
    } catch (Exception e) { 
     System.out.println("Internet connection not available :("); 
    } 
} 

起初,我试图打开没有代理的URL连接(假设系统没有代理连接互联网)。我已经将超时设置为1毫秒。尝试从网站获取响应代码。 如果发生任何错误意味着(如超时),则在catch块中,我尝试通过将系统的代理连接到Internet,方法是将useSystemProxies设置为true。 但即使在此之后,我也无法从网站得到回应。

我正在使用代理设置的系统。

我曾尝试在catch块

Proxy next = ProxySelector.getDefault().select(new URI("http://www.google.com/")).iterator().next(); 
if (next.address() != null) { 
    System.out.println("Detecting Proxy configurations....."); 
    String proxy = next.address().toString(); 
    String proxyHost = proxy.substring(0, proxy.indexOf(":")); 
    String proxyPort = proxy.substring(proxy.indexOf(":") + 1); 
    System.out.println("Proxy Configuration : " + proxyHost + " @ " + proxyPort); 
} 

上面的代码块也不是工作压力太大以下。任何人都可以帮我解决这个问题吗?

回答

0

InetAddress.isReachable

该地址测试是否可达。尝试通过 实现尝试访问主机,但尝试访问主机时会尽最大努力,但防火墙和服务器配置可能会阻止导致无法访问状态的请求,而某些特定端口可能是可访问的。如果可以获得特权,典型实现 将使用ICMP ECHO请求,否则它将尝试在目的地主机的端口7(Echo) 上建立TCP连接。超时值(以毫秒为单位)表示尝试应采取的最长时间量为 。如果在获得答案之前操作时间为 ,主机将被视为无法访问。 A 负值将导致抛出IllegalArgumentException异常为 。

0

在catch块的第一个代码片段中,尝试设置以下代码。

System.setProperty("http.proxyHost", "Proxy host"); 
System.setProperty("http.proxyPort", "Proxy Port"); 

似乎您的代理已注册为系统代理,并且对JVM不可见。