加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何使用URLConnection超时

发布时间:2020-12-15 01:10:53 所属栏目:Java 来源:网络整理
导读:我正在尝试排序SOCKS代理列表,并找出哪些连接和读取时间小于1000毫秒,这是我的代码 for(Proxy p : proxies) { try { URLConnection testConnection = testUrl.openConnection(p); testConnection.setConnectTimeout(TIMEOUT_VALUE); testConnection.setReadT

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读