本文介绍了如何为OkHttpClient设置连接超时? 2017年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很容易说它是重复的,但不是.

我读了很多关于如何在android中设置连接超时的文章,但该文章已有4-7年的历史,我认为我们都需要更新此主题,因为这些方法已被弃用或不再存在. /p>

所以问题是我在等待服务器响应时如何设置连接超时?

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

if (response.isSuccessful()) {
                          //success
} else {
       //unsuccessful
}
解决方案

如果通过OkHttpClient.Builder创建OkHttpClient,则可以使用connectTimeout()readTimeout()writeTimeout()方法调用各种超时选项.

如果您需要为特定的HTTP请求覆盖它们,请在OkHttpClient上调用newBuilder().这样您将获得一个OkHttpClient.Builder,其设置与您最初使用的设置相同. 您可以根据需要覆盖它们,并创建一个临时Builder中的c1>,将其用于此一次性呼叫.

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
}
解决方案

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.

这篇关于如何为OkHttpClient设置连接超时? 2017年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 11:33