且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 URLConnection 超时

更新时间:2022-03-10 05:07:42

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

I assume your problem is you don't read anything from connection. If I set TIMEOUT_VALUE too 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.

这是我使用的测量(没有代理):

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