【发布时间】:2020-08-14 12:59:27
【问题描述】:
我正在使用 RxAndroid + Retrofit 来发出 http 请求。代码如下:
Interceptor headerInterceptor = getHeaderInterceptor();
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.callTimeout(5, TimeUnit.SECONDS)
.addInterceptor(headerInterceptor)
.addInterceptor(httpLoggingInterceptor)
.build();
Gson gson = new GsonBuilder()
.setLenient()
.create();
sRetrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
像这样使用它:
ApiProvider.provideApi(MyApi.class)
.submit(id, mRequest)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
response -> {
Log.w("tag", "success");
},
throwable -> {
Log.w("tag", "error");
}
);
我将connectTimeout / readTimeout / writeTimeout设置为60秒,将callTimeout设置为5秒。
我知道这个配置可能不合理但我只想在5秒后得到一个超时异常,并且可以调用Log.w("tag", "error");。
但是,我发现我的测试永远不会调用这条线。如果我将connectionTimeout 设置为 1 秒,那么将立即调用此行。
那么如果我想让 callTimeout 触发日志错误行该怎么办呢?
【问题讨论】:
-
尝试添加
.retryOnConnectionFailure(false) -
5 秒的通话超时非常少...大约 50 秒或 1 分钟。
-
@AntonisRadz 尝试了
retryOnConnectionFailure(false),不起作用。但还是谢谢你们! -
@PrajwalW 嗯,我同意 5 秒太短,但如果我将连接超时设置为 1 秒,代码运行良好,我可以调用
onError。谢谢! -
正如你提到的,连接超时似乎小于呼叫超时。请尝试一次。设置调用超时值 > 连接超时值。
标签: android retrofit rx-java okhttp rx-android