HttpURLConnection setConnectTimeout() has no effect

前端 未结 8 1541
刺人心
刺人心 2020-12-04 21:40

I\'m connecting to a simple RSS feed using HTTPUrlConnection. It works perfectly. I\'d like to add a timeout to the connection since I don\'t want my app hanging in the even

8条回答
  •  孤城傲影
    2020-12-04 22:27

    You probably either/both:
    1) Don't read anything from connection
    2) Don't catch & handle the exception properly

    As mentioned here, use logic similar to this:

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

提交回复
热议问题