Cómo establecer el tiempo de espera de conexión con OkHttp


Estoy desarrollando una aplicación usando la biblioteca OkHttp y mi problema es que no puedo encontrar cómo establecer el tiempo de espera de conexión y el tiempo de espera del socket.

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder().url(url).build();

Response response = client.newCall(request).execute();

Gracias.

Author: einverne, 2014-09-21

10 answers

Simplemente tienes que hacer esto

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(15, TimeUnit.SECONDS); // connect timeout
client.setReadTimeout(15, TimeUnit.SECONDS);    // socket timeout

Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();

Ser consciente de que el conjunto de valores en setReadTimeout es el utilizado en setSoTimeout en el Socket internamente en el OkHttp Connection clase.

No establecer ningún tiempo de espera en el OkHttpClient es el equivalente de establecer un valor de 0 en setConnectTimeout o setReadTimeout y dará lugar a ningún tiempo de espera en absoluto. La descripción se puede encontrar aquí.

Como menciona @marceloquinta en los comentarios setWriteTimeout también se puede establecer.

A partir de la versión 2.5.0 leer / los valores de tiempo de espera de escritura / conexión se establecen de forma predeterminada en 10 segundos, como menciona @ChristerNordvik. Esto se puede ver aquí.

A partir de OkHttp3 ahora puede hacer esto a través del Constructor así

client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();

También puedes ver la receta aquí

 241
Author: Miguel Lavigne,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-05 19:17:05

Para okhttp3 esto ha cambiado un poco.

Ahora configura los tiempos usando el constructor, y no los configuradores, de esta manera:

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build();

Se puede encontrar más información en su wiki: https://github.com/square/okhttp/wiki/Recipes#timeouts

 101
Author: Kaizie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-05 01:52:42

Para Retrofit retrofit: 2.0.0-beta4 el código es el siguiente

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .connectTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS)
        .build();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://api.yourapp.com/")
        .addConverterFactory(GsonConverterFactory.create())
        .client(client)
        .build();
 10
Author: Sam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-25 07:16:11

Para Retrofit 2.0.0-beta1 o beta2, el código es el siguiente

    OkHttpClient client = new OkHttpClient();

    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://api.yourapp.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build();
 8
Author: xaxist,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-28 10:30:39
//add in gradle and sync
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'

import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;


Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties

OkHttpClient client = b.build();
 6
Author: Mohammad nabil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-08 05:55:05

Así:

//New Request
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BASIC);
        final OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
 3
Author: Joolah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-06 09:07:00

Ahora ha cambiado. Sustitúyase .Builder() por .newBuilder()

De okhttp:3.9.0 el código es el siguiente:

OkHttpClient okHttpClient = new OkHttpClient()
    .newBuilder()
    .connectTimeout(10,TimeUnit.SECONDS)
    .writeTimeout(10,TimeUnit.SECONDS)
    .readTimeout(30,TimeUnit.SECONDS)
    .build();
 3
Author: Leo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-19 12:13:18

Esto funcionó para mí ... de https://github.com/square/okhttp/issues/3553

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .retryOnConnectionFailure(false) <-- not necessary but useful!
        .build();
 3
Author: rHenderson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-19 15:12:13

Si desea personalizar la configuración, utilice la siguiente metodología de crear OkHttpClient primero y luego agregue builder encima.

private final OkHttpClient client = new OkHttpClient();

// Copy to customize OkHttp for this request.
    OkHttpClient client1 = client.newBuilder()
        .readTimeout(500, TimeUnit.MILLISECONDS)
        .build();
    try (Response response = client1.newCall(request).execute()) {
      System.out.println("Response 1 succeeded: " + response);
    } catch (IOException e) {
      System.out.println("Response 1 failed: " + e);
    }
 1
Author: sandhya murugesan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-30 07:39:09

Versión Okhttp: 3.11.0 o superior

Del código fuente okhttp

/**
 * Sets the default connect timeout for new connections. A value of 0 means no timeout,
 * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to
 * milliseconds.
 *
 * <p>The connectTimeout is applied when connecting a TCP socket to the target host.
 * The default value is 10 seconds.
 */
public Builder connectTimeout(long timeout, TimeUnit unit) {
  connectTimeout = checkDuration("timeout", timeout, unit);
  return this;
}

unit puede ser cualquier valor de abajo

TimeUnit.NANOSECONDS
TimeUnit.MICROSECONDS
TimeUnit.MILLISECONDS
TimeUnit.SECONDS
TimeUnit.MINUTES
TimeUnit.HOURS
TimeUnit.DAYS

Código de ejemplo

OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(5000, TimeUnit.MILLISECONDS)/*timeout: 5 seconds*/
        .build();

String url = "https://www.google.com";
Request request = new Request.Builder()
        .url(url)
        .build();

try {
    Response response = client.newCall(request).execute();
} catch (IOException e) {
    e.printStackTrace();
}
 0
Author: shellhub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-17 11:44:31