【问题标题】:Retrofit with kotlin throws Failed to connect to {ServerName/IpAddress}使用 kotlin 进行改造会引发无法连接到 {ServerName/IpAddress}
【发布时间】:2020-08-06 05:44:17
【问题描述】:

我在使用 retrofit2 和 kotlin 时遇到了奇怪的问题。我是 Kotlin 的新手。 当我点击一个 API 超过 6 次时,我收到此 Failed to connect to {ServerName/IpAddress} 错误。

这是接口的代码

 companion object {
    lateinit var context: Context
    private fun getHttpClient(): OkHttpClient.Builder {
       return OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .addInterceptor(HttpLoggingInterceptor().apply {
                    level = if(BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
                })
    }
    fun retrofitBuilder(): Retrofit.Builder {
        val gson = GsonBuilder().setLenient().create()
        return Retrofit.Builder()
                .baseUrl(AppConstants.BASE_URL)
                //.addConverterFactory(ToStringConverterFactory())
                .addConverterFactory(GsonConverterFactory.create(gson))
    }

    fun create(): ApiInterface {
        val gson = GsonBuilder().setLenient().create()
        val retrofit = retrofit2.Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create(gson))
                .baseUrl(AppConstants.BASE_URL)
                .client(getHttpClient().build())
                .build()

        return retrofit.create(ApiInterface::class.java)
    }

    fun createWithAuth(context: Context, token: String?): ApiInterface {
        this.context = context
        val httpClient = getHttpClient()

        httpClient.addInterceptor { chain ->
            val req = chain.request()
            val request = chain.request().newBuilder()
                    .addHeader("Authorization", "Bearer $token")
                    .addHeader("Accept-Encoding", "None")
                    .method(req.method, req.body)
                    .build()
            chain.proceed(request)
        }

        val retrofits = retrofitBuilder().client(httpClient.build()).build()
        return retrofits.create(ApiInterface::class.java)
    }
}

我检查了服务器是否有问题,但我通过使用 Runner 在循环中访问相同的 API 100 次来检查 Postman。 Postman 每次都返回成功响应。

请帮帮我。

谢谢。

【问题讨论】:

    标签: android api kotlin server retrofit


    【解决方案1】:

    在上面的问题中,Companion Object {} 中的代码是在我的端点所在的接口类中编写的。

    并创建了这个类,类似于上面的代码,但作为一个单独的类。

    class ApiClient private constructor() {
    companion object {
        private val retrofit: Retrofit? = null
        private var context: Context? = null
    
    
        private val httpClient: OkHttpClient.Builder = OkHttpClient.Builder()
                //.addInterceptor(LoggingInterceptor())
    
    
        private val builder: Retrofit.Builder = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
    
        fun  createService(ctx: Context): ApiInterface {
            context = ctx
            val retrofit: Retrofit = builder.client(httpClient.build()).build()
            return retrofit.create(ApiInterface::class.java)
        }
    
    
        fun createServiceWithAuth(ctx: Context, authToken: String?): ApiInterface {
            context = ctx
            if (authToken != null) {
                httpClient.addInterceptor(object : Interceptor {
                    @Throws(IOException::class)
                    override fun intercept(chain: Interceptor.Chain): Response {
                        val original: Request = chain.request()
                        val request: Request = original.newBuilder() //.header("User-Agent", "Your-App-Name")
                                .header("Authorization", "bearer $authToken")
                                .header("Accept-Encoding", "None")
                                .method(original.method, original.body)
                                .build()return chain.proceed(request)
                    }
                })
            }
            val retrofit: Retrofit = builder.client(httpClient.build()).build()
            return retrofit.create(ApiInterface::class.java)
        }
      }
    }
    

    我仍然不明白这两个代码中的问题{问题问,这个答案}。但是这个答案并没有给我这样的问题。

    如果有人可以解释我,这将对我和其他人都有帮助。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 2013-02-05
      • 2021-10-21
      • 2013-03-12
      • 2017-12-10
      • 1970-01-01
      相关资源
      最近更新 更多