系统的互联网连接我写了一个方法,这将有助于我们发现使用代理系统是否与网上有如下连接,检查使用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);
}
上面的代码块也不是工作压力太大以下。任何人都可以帮我解决这个问题吗?