簡體   English   中英

使用Java檢查系統的Internet連接

[英]Checking internet connectivity of a system using 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連接(假設系統沒有與Internet連接的代理)。我將超時設置為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);
}

上面的代碼塊也不起作用。 誰能幫我這個忙嗎?

InetAddress.isReachable

測試該地址是否可訪問。 該實現會盡最大努力嘗試到達主機,但是防火牆和服務器配置可能會阻止請求,從而導致無法訪問狀態,同時某些特定端口可能可以訪問。 如果可以獲得特權,則典型的實現將使用ICMP ECHO REQUEST,否則,它將嘗試在目標主機的端口7(Echo)上建立TCP連接。 超時值(以毫秒為單位)表示嘗試應花費的最長時間。 如果操作在獲得答案之前超時,則認為主機不可訪問。 負值將導致拋出IllegalArgumentException。

在catch代碼塊的第一個代碼段中,嘗試設置以下代碼。

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

似乎您的代理已注冊為系統代理,並且對JVM不可見。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM