重庆分公司,新征程启航
为企业提供网站建设、域名注册、服务器等服务
本文介绍了Kotlin + Retrofit + RxJava简单封装使用详解,分享给大家,具体如下:
专注于为中小企业提供成都网站建设、网站制作服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业通城免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了成百上千家企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。实例化Retrofit
object RetrofitUtil { val CONNECT_TIME_OUT = 30//连接超时时长x秒 val READ_TIME_OUT = 30//读数据超时时长x秒 val WRITE_TIME_OUT = 30//写数据接超时时长x秒 val retrofit: Retrofit by lazy { Log.d("RetrofitUtil", "retrofit init lazy") Retrofit.Builder() .baseUrl("http://gank.io/api/") //本文以GitHub API为例 .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .client(getOkHttpClient()) .build() } private fun getOkHttpClient(): OkHttpClient { val builder = OkHttpClient.Builder() builder.connectTimeout(CONNECT_TIME_OUT.toLong(), TimeUnit.SECONDS) .writeTimeout(WRITE_TIME_OUT.toLong(), TimeUnit.SECONDS) .readTimeout(READ_TIME_OUT.toLong(), TimeUnit.SECONDS) if (BuildConfig.DEBUG) { builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) } else { builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.NONE)) } // 设置请求头 builder.addInterceptor { chain -> val time = (System.currentTimeMillis() / 1000).toString() + "" val requestBuilder = chain.request().newBuilder() requestBuilder.addHeader("time", time) chain.proceed(requestBuilder.build()) } return builder.build() } }