java - How to set timeout in Retrofit library? -


i using retrofit library in app, , i'd set timeout of 60 seconds. retrofit have way this?

i set retrofit way:

restadapter restadapter = new restadapter.builder()     .setserver(buildconfig.base_url)     .setconverter(new gsonconverter(gson))     .build(); 

how can set timeout?

you can set timeouts on underlying http client. if don't specify client, retrofit create 1 default connect , read timeouts. set own timeouts, need configure own client , supply restadapter.builder.

an option use okhttp client, square.

1. add library dependency

in build.gradle, include line:

compile 'com.squareup.okhttp:okhttp:x.x.x' 

where x.x.x desired library version.

2. set client

for example, if want set timeout of 60 seconds, way retrofit before version 2 , okhttp before version 3 (for newer versions, see edits):

public restadapter providesrestadapter(gson gson) {     final okhttpclient okhttpclient = new okhttpclient();     okhttpclient.setreadtimeout(60, timeunit.seconds);     okhttpclient.setconnecttimeout(60, timeunit.seconds);      return new restadapter.builder()         .setendpoint(buildconfig.base_url)         .setconverter(new gsonconverter(gson))         .setclient(new okclient(okhttpclient))         .build(); } 

edit 1

for okhttp versions since 3.x.x, have set client using builder pattern, way:

final okhttpclient okhttpclient = new okhttpclient.builder()         .readtimeout(60, timeunit.seconds)         .connecttimeout(60, timeunit.seconds)         .build(); 

more info in timeouts

edit 2

retrofit versions since 2.x.x uses builder pattern, change return block above this:

return new retrofit.builder()     .baseurl(buildconfig.base_url)     .addconverterfactory(gsonconverterfactory.create())     .client(okhttpclient)     .build(); 

if using code providesrestadapter method, change method return type retrofit.

more info in retrofit 2 — upgrade guide 1.9


ps: if minsdkversion greater 8, can use timeunit.minutes:

okhttpclient.setreadtimeout(1, timeunit.minutes); okhttpclient.setconnecttimeout(1, timeunit.minutes); 

for more details units, see timeunit.


Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -