【问题标题】:Retrofit SocketTimeoutException Error When API is DownAPI关闭时改造SocketTimeoutException错误
【发布时间】:2021-09-30 04:01:45
【问题描述】:

我正在尝试创建一个Interceptor,以防我使用的 API 出现故障,当我尝试对 Postman 进行 API 调用时发生这种情况,只是为了返回 504 错误。

这是我现在拥有的OkHttpClient。我将其设置为 5 秒仅用于测试目的。

val client = OkHttpClient.Builder()
    .connectTimeout(5, TimeUnit.SECONDS)
    .writeTimeout(5, TimeUnit.SECONDS)
    .readTimeout(5, TimeUnit.SECONDS)
    .addInterceptor(object : Interceptor {
        override fun intercept(chain: Interceptor.Chain): okhttp3.Response  {
            val response = chain.proceed(chain.request())
            when (response.code()) {
                504 -> {
                    //Show Bad Request Error Message
                }
            }
            return response
        }
    })
    .build()

searchRetrofit = Retrofit.Builder()
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl(URL)
    .client(client)
    .build()

稍后在代码中,我使用 Retrofit 的 execute() 方法对 API 进行同步调用。 execute() 行和 val response = chain.proceed(chain.request()) 如果 API 服务关闭或检索结果花费的时间太长,我的应用程序会崩溃。我收到 java.net.SocketTimeoutException 错误。

当我使用的 API 服务关闭时,我可以做些什么来防止我的应用崩溃?我可以在Interceptor 中添加什么,或者我应该在try catch 语句中包围我的execute() 调用?

【问题讨论】:

    标签: android kotlin retrofit retrofit2 okhttp


    【解决方案1】:

    正确的解决方案是使用enqueue 而不是executesynchronous 网络调用几乎总是一个坏主意,因为您不想阻塞调用线程。使用enqueue 你应该这样做

    call.enqueue(object : Callback<SomeResponse> {
        override fun onFailure(call: Call<SomeResponse>?, t: Throwable?) {
            // This code will be called when your network call fails with some exception
            // SocketTimeOutException etc
        }
    
        override fun onResponse(call: Call<SomeResponse>?, response: Response<SomeResponse>?) {
            // This code will be called when response is received from network
            // response can be anything 200, 504 etc
        }
    })
    

    如果您必须使用execute,那么至少您必须将您的执行调用附在try catch

    try{
        call.execute()
    }
    catch(e: Exception){
         // Process any received exception (SocketTimeOutEtc)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      相关资源
      最近更新 更多