我写了一个方法,可以帮助我们找到系统是否使用代理连接互联网,如下所示,
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
. 但即使在那之后,我也无法得到该网站的回复。
我正在使用具有代理设置的系统。
我在 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);
}
上面的代码块也不起作用。谁能帮我解决这个问题?