How can I set connection timeout for OkHttpClient? 2017

橙三吉。 提交于 2019-12-13 00:07:19

问题


It is easy to say it's duplicate but it isn't.

I read many post about how to set the connection timeout in android but the post are 4-7 years old and I think that we all need an update about this topic because those methods are deprecated or no longer exist.

So the question is how can I set my connection timeout when I am waiting for a response from the server?

final Response response = httpClient.newCall(request).execute();

if (response.isSuccessful()) {
                          //success
} else {
       //unsuccessful
}

回答1:


If you create your OkHttpClient through an OkHttpClient.Builder, there are connectTimeout(), readTimeout(), and writeTimeout() methods that you can call for the various timeout options.

If you need to override them for a specific HTTP request, call newBuilder() on your OkHttpClient. That gives you an OkHttpClient.Builder with the same settings as you used originally. You can override those as needed, and create a temporary OkHttpClient from the new Builder, using that for this one-off call.



来源:https://stackoverflow.com/questions/44620389/how-can-i-set-connection-timeout-for-okhttpclient-2017

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!