How to use URLConnection Timeout

帅比萌擦擦* 提交于 2019-11-28 10:23:09

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

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");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!