Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default timeout for HttpURLConnection under Android?

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 ?

like image 311
zeus Avatar asked Mar 07 '23 13:03

zeus


1 Answers

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
like image 85
3 revs, 2 users 99% Avatar answered Mar 10 '23 12:03

3 revs, 2 users 99%