如何使用OkHttp设置连接超时

我正在开发应用程序使用OkHttp库,我的麻烦是我无法find如何设置连接超时和套接字超时。

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

谢谢。

你只需要做到这一点

 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(); 

请注意setReadTimeout设置的setReadTimeout是在setSoTimeoutSocket内部的OkHttp中使用的OkHttp

OkHttpClient上不设置任何超时值相当于在setConnectTimeoutsetReadTimeout上设置一个0值,并且根本不会造成超时。 说明可以在这里find。

正如@marceloquinta在setWriteTimeout所提到的,也可以这样设置。

从版本2.5.0开始,读/写/连接超时值默认设置为10秒,如@ChristerNordvik所述。 这可以在这里看到。

至于OkHttp3现在可以通过Builder来做到这一点

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

您也可以在这里查看配方

对于okhttp3这已经改变了一下。

现在你用build设者设置时间,而不是像这样设置设置器:

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

更多信息可以在他们的wiki中find: https : //github.com/square/okhttp/wiki/Recipes#timeouts

对于改造改造:2.0.0-beta4的代码如下

 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(); 

对于Retrofit 2.0.0-beta1或beta2,代码如下

  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(); 
 //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(); 

像这样:

 //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(); 

现在改变了。 用.Builder()replace.newBuilder()

截至okhttp:3.9.0如下图所示:

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