4

What is the default read and connect timeout for HttpURLConnection under android?

It's seam the default Timeout is 0, but now I m curious, is their any drawback to set the connection timeout to infinite? if something goes wrong can we have a connection that will forever wait ?

zeus
  • 12,173
  • 9
  • 63
  • 184

1 Answers1

7

A - Documentation

Due to the documentation of Java of the HttpURLConnection, timeout is set to 0 (which means infinity) by default and can be modified.

Specifically, it is written in the accessor/getter method in the documentation;

public int getConnectTimeout() Returns setting for connect timeout. 0 return implies that the option is disabled (i.e., timeout of infinity).

Returns: an int that indicates the connect timeout value in milliseconds Since: 1.5 See Also: setConnectTimeout(int), connect()

If I were you, I would set the connection timeout before starting the connection and set my logic/flow based on my own initial values. Below, you can see an example for how to get the default value and set/modify the connection timeout parameter.

B - Example Code

package com.levo.so.huc;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpConnectionTimeoutDemo {

    public static void main(String[] args) throws IOException {
        String url = "http://www.google.com/";

        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        
        System.out.println("Default Connection Timeout : " + con.getConnectTimeout());
        
        con.setConnectTimeout(1000);
        System.out.println("New Connection Timeout     : " + con.getConnectTimeout());

    }

}

C - Output

Default Connection Timeout : 0
New Connection Timeout     : 1000
Kelvin Bouma
  • 179
  • 1
  • 2
  • 12
Levent Divilioglu
  • 11,198
  • 5
  • 59
  • 106
  • 1
    Thanks ! i update also a little the question because i m curious to know if setting by default timeout to infinite can not lead to some problem – zeus Mar 30 '18 at 22:48