Java 如何使用 URLConnection 超时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6529733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:41:30  来源:igfitidea点击:

How to use URLConnection Timeout

javaproxysocks

提问by Austin

I am trying to sort through a list of SOCKS proxies, and figure out which ones have a connect and read time of less than 1000ms, here is my code

我正在尝试对 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.");
            }
        }

But every single one of them passes the test, even when I do TIMEOUT_VALUE = 1;What am I doing wrong? Thanks for any help.

但是他们中的每一个都通过了测试,即使我做TIMEOUT_VALUE = 1;我做错了什么?谢谢你的帮助。

采纳答案by Thresh

I assume your problem is you don't read anything from connection. If I set TIMEOUT_VALUEtoo low, I get an exception. Whether I read all response or only one line did not affect the resulting time, I guess it is because I got whole answer in one packet.

我认为您的问题是您没有从连接中读取任何内容。如果我设置TIMEOUT_VALUE得太低,我会得到一个例外。无论我阅读所有响应还是仅阅读一行都不会影响结果时间,我想这是因为我在一个数据包中得到了完整的答案。

Here is the measurement I used (without proxies):

这是我使用的测量值(无代理):

    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.");
    }

回答by Ronald

I use

我用

    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");