使用Java检查系统的Internet连接

时间:2013-03-28 06:41:17

标签: java proxy httpurlconnection

我写了一个方法,它将帮助我们查找使用代理连接互联网的系统是否如下,

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块中我试图通过将useSystemProxies设置为true来尝试使用系统代理连接到Internet。 但即使在那之后,我也无法得到该网站的回复。

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

我在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);
}

上面的代码块也无效。任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

InetAddress.isReachable

  

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

答案 1 :(得分:0)

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

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

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