使用Java检查系统的internet连接

使用Java检查系统的internet连接,java,proxy,httpurlconnection,Java,Proxy,Httpurlconnection,我写了一个方法,它将帮助我们找到系统是否使用代理连接到internet,如下所示 try { System.out.println("Checking internet connection availability....."); URL u = new URL("http://www.google.com/"); HttpURLConnection uc = (HttpURLConnection) u.openConnection(); uc.setRead

我写了一个方法,它将帮助我们找到系统是否使用代理连接到internet,如下所示

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连接(假设系统没有代理连接到internet)。我已将超时设置为1毫秒。尝试从站点获取响应代码。 如果通过设置
useSystemProxies
true
的方式出现任何错误(如超时),则在catch块中,我正试图通过系统的代理连接到internet。 但即使在那之后,我也无法从网站上得到回复

我使用的是带有代理设置的系统

我也试过以下的方法

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);
}
上述代码块也不起作用。有人能帮我解决这个问题吗?

测试该地址是否可访问。尽最大努力是由 实现尝试到达主机,但防火墙和服务器 配置可能会阻止导致无法访问状态的请求 而某些特定端口可能是可访问的。典型的实现 如果可以获得特权,将使用ICMP回显请求, 否则,它将尝试在端口7(Echo)上建立TCP连接 目标主机的名称。超时值(以毫秒为单位)表示 尝试所需的最长时间。如果手术时间 在得到答复之前,主机被视为无法访问。A. 负值将导致出现IllegalArgumentException 扔

测试该地址是否可访问。尽最大努力是由 实现尝试到达主机,但防火墙和服务器 配置可能会阻止导致无法访问状态的请求 而某些特定端口可能是可访问的。典型的实现 如果可以获得特权,将使用ICMP回显请求, 否则,它将尝试在端口7(Echo)上建立TCP连接 目标主机的名称。超时值(以毫秒为单位)表示 尝试所需的最长时间。如果手术时间 在得到答复之前,主机被视为无法访问。A. 负值将导致出现IllegalArgumentException 扔


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

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

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

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

System.setProperty("http.proxyHost", "Proxy host");
System.setProperty("http.proxyPort", "Proxy Port");
似乎您的代理已注册为系统代理,JVM不可见