簡體   English   中英

如何使用 URLConnection 超時

[英]How to use URLConnection Timeout

我正在嘗試對 SOCKS 代理列表進行排序,並找出哪些代理的連接和讀取時間小於 1000 毫秒,這是我的代碼

for(Proxy p : proxies) {
            try {
            URLConnection testConnection = testUrl.openConnection(p);
            testConnection.setConnectTimeout(TIMEOUT_VALUE);
            testConnection.setReadTimeout(TIMEOUT_VALUE);
            success.add(p);
            } catch(SocketTimeoutException ste) {
                System.out.println("Proxy " + p.address().toString() + " timed out.");
            }
        }

但是他們每個人都通過了測試,即使我做TIMEOUT_VALUE = 1; 我究竟做錯了什么? 謝謝你的幫助。

我認為您的問題是您沒有從連接中讀取任何內容。 如果我將TIMEOUT_VALUE設置得太低,則會出現異常。 無論我閱讀所有響應還是僅一行都不會影響結果時間,我想這是因為我在一個數據包中得到了完整的答案。

這是我使用的測量值(沒有代理):

    int TIMEOUT_VALUE = 1000;
    try {
        URL testUrl = new URL("http://google.com");
        StringBuilder answer = new StringBuilder(100000);

        long start = System.nanoTime();

        URLConnection testConnection = testUrl.openConnection();
        testConnection.setConnectTimeout(TIMEOUT_VALUE);
        testConnection.setReadTimeout(TIMEOUT_VALUE);
        BufferedReader in = new BufferedReader(new InputStreamReader(testConnection.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            answer.append(inputLine);
            answer.append("\n");
        }
        in.close();

        long elapsed = System.nanoTime() - start;
        System.out.println("Elapsed (ms): " + elapsed / 1000000);
        System.out.println("Answer:");
        System.out.println(answer);
    } catch (SocketTimeoutException e) {
        System.out.println("More than " + TIMEOUT_VALUE + " elapsed.");
    }

我用

    System.getProperties().put("proxySet", "true");
    System.getProperties().put("http.proxyHost", "192.168.10.121");
    System.getProperties().put("http.proxyPort", "8080");
    //System.getProperties().put("http.nonProxyHosts", "8080");

暫無
暫無

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

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