如何在 Kotlin android 的改造中使用 enque 方法

Posted

技术标签:

【中文标题】如何在 Kotlin android 的改造中使用 enque 方法【英文标题】:How to use enque method in retrofit in Kotlin android 【发布时间】:2018-09-09 10:06:05 【问题描述】:

我正在尝试使用改造和 kotlin 语言从 Web 服务获得响应。但我无法调用 enque 方法。

这是改造客户

    class WebService() 

    companion object 
        fun createService(isAddToken: Boolean): WebServiceApi 
            val logging = HttpLoggingInterceptor()
            val httpClient = OkHttpClient.Builder()
            var retrofit: Retrofit

            httpClient.addInterceptor  chain ->
                val original = chain.request()
                val requestBuilder = original.newBuilder()
                        .header(CONTENT_TYPE, "application/json")
                        .header(API_USER_NAME, AUTH_USERNAME)
                        .header(API_PASSWORD, AUTH_PASSWORD)
                        .header(LANGUAGE_CODE, "en")
                if (isAddToken) 
                    requestBuilder.header(TOKEN,
                            "" /*DataGenerator.getAuthToken(context)*/)
                

                requestBuilder.method(original.method(), original.body())
                val request = requestBuilder.build()
                chain.proceed(request)
            

            // set your desired log level
            if (BuildConfig.DEBUG) 
                logging.level = HttpLoggingInterceptor.Level.BODY
                // add logging as last interceptor
                httpClient.addInterceptor(logging)
            

            // Timeout handling
            val client = httpClient.readTimeout(20,
                    TimeUnit.SECONDS)
                    .connectTimeout(20, TimeUnit.SECONDS)
                    .writeTimeout(20, TimeUnit.SECONDS)
                    .build()

            if (BuildConfig.DEBUG) 
                retrofit = Retrofit.Builder()
                        .baseUrl(WebServiceConstants.LIVE_BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client)
                        .build()
             else 
                retrofit = Retrofit.Builder()
                        .baseUrl(WebServiceConstants.LIVE_BASE_URL)
                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client)
                        .build()

            

            return retrofit.create(WebServiceApi::class.java);
        
    

这是我在按钮上调用 api 的 MainActivity 代码

 val parameterOTP = SendParameterOTP()
 parameterOTP.phoneNumber = phoneNumber

 var serviceAPI = WebService.createService(false)
 serviceAPI.enque() \\Unable to understand how i call enques**

我尝试了使用 rxjava 的示例,它工作正常。但是我想使用 enque 方法,因为我想实现自定义回调以进行重试。请帮忙

【问题讨论】:

【参考方案1】:

尝试使用这个:

val call = createService(isAddToken).methodNameInWebServiceApi(params)
            call.enqueue(object : Callback<ResponseObject> 
                override fun onFailure(call: Call<ResponseObject>?, t: Throwable?) 
                    Log.e("erroe", "")
                

                override fun onResponse(call: Call<ResponseObject>?, response: Response<ResponseObject>?) 

                
            )

【讨论】:

【参考方案2】:

我正在使用 kotlin 提供改造类和 api 调用,并根据您身边的 rxjava 进行更改。

class ApiClient 

companion object 
    val BASE_URL = "https://simplifiedcoding.net/demos/"
    var retrofit: Retrofit? = null
    fun getClient(): Retrofit? 
        if (retrofit == null) 
            val interceptor = HttpLoggingInterceptor()
            interceptor.level = HttpLoggingInterceptor.Level.BODY
            val client = OkHttpClient.Builder().apply 
            readTimeout(20, TimeUnit.SECONDS)
            writeTimeout(20, TimeUnit.SECONDS)
            connectTimeout(20, TimeUnit.SECONDS)
            addInterceptor(interceptor)
            addInterceptor  chain ->
                var request = chain.request()
                request = request.newBuilder()
                        .build()
                val response = chain.proceed(request)
                response
            
            
            retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client.build())

                    .addConverterFactory(GsonConverterFactory.create())
                    .build()

        

        return retrofit
    

然后在使用下面的代码进行api调用之后..

 var apiInterface: ApiInterface = ApiClient.getClient()!!.create(ApiInterface::class.java)
    var hero: Call<List<Hero>>
    hero = apiInterface.getData()
    hero.enqueue(object : Callback<List<Hero>> 
        override fun onFailure(call: Call<List<Hero>>?, t: Throwable?) 
            closeDialog(dialog)
            Toast.makeText(mContext, t?.message, Toast.LENGTH_SHORT).show()
            Log.d("Error:::",t?.message)
        

        override fun onResponse(call: Call<List<Hero>>?, response: Response<List<Hero>>?) 
           mHeroDataList.clear()
            if (response != null && response.isSuccessful && response.body() != null) 
                closeDialog(dialog)
                mHeroDataList .addAll(response.body()!!)
                setAdapter(mHeroDataList)
            
        

    )

【讨论】:

【参考方案3】:

app > build.gradle

//    Retrofit
implementation ("com.squareup.retrofit2:retrofit:$retrofit_version") 
    // exclude Retrofit’s OkHttp peer-dependency module and define your own module import
    exclude module: "okhttp"


//    OkHttp and a logging interceptor
implementation("com.squareup.okhttp3:okhttp:$okhttp_version")
implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version"

项目 > build.gradle

buildscript 
    ...
    ext.retrofit_version = '2.6.0'
    ext.okhttp_version = '4.0.0'
    ...

package.name > 外部 > ApiClient.kt

object ApiClient 

    private const val BASE_URL = "https://test.apiary-mock.com/"

    private var retrofit: Retrofit? = null

    val apiClient: Retrofit
        get() 
            if (retrofit == null) 
                val logging = HttpLoggingInterceptor()
                logging.apply 
                    level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
                

                val client: OkHttpClient = OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .build()

                retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
            
            return retrofit!!
        

用法

val carRestService = ApiClient.apiClient.create(CarRestService::class.java)

来源

exclude module okhttp okhttp-logging-interceptor

【讨论】:

以上是关于如何在 Kotlin android 的改造中使用 enque 方法的主要内容,如果未能解决你的问题,请参考以下文章

如何将 localhost 与改造结合使用来测试 android 应用程序 kotlin [重复]

如何从改造响应 kotlin android 下载图像

如何在Android上的Kotlin类中使用上下文

如何使用 Retrofit Android Kotlin 发布 [重复]

如何使用 Kotlin 在 Android Studio 的字符串列表中转换 StringBuilder 项?

kotlin android中的改造请求@Part和@Query