首先创建个retrofit的单列
/**
* Created by JokAr on 2017/6/5.
*/
class NetworkConfig private constructor() {
private val DEFAULT_TIMEOUT: Long = 15
private val BASE_URL: String = "http://gank.io/api"
var retrofit: Retrofit = initRetrofit()
private object Holder { val INSTANCE = NetworkConfig() }
companion object{
val instance:NetworkConfig by lazy { Holder.INSTANCE }
}
private fun initRetrofit(): Retrofit {
val interceptor = HttpLoggingInterceptor()
if (BuildConfig.DEBUG)
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
else
interceptor.setLevel(HttpLoggingInterceptor.Level.NONE)
val client = OkHttpClient.Builder()
.addInterceptor(interceptor)
.retryOnConnectionFailure(true)
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl(BASE_URL + "/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
}
然后创建请求service
/**
* Created by JokAr on 2017/6/5.
*/
interface DataService {
@GET("data/{type}/{count}/{pageSize}")
fun getData(@Path("type") type: String,
@Path("count") count: Int,
@Path("pageSize") pageSize: Int)
: Observable<HttpResult<ArrayList<DataEntities>>>
}
其中HttpResult
和DataEntities
元素类为
/**
* Created by JokAr on 2017/6/5.
*/
data class DataEntities(@SerializedName("_id") var _id: String,
@SerializedName("createdAt") var createdAt: String,
@SerializedName("desc") var desc: String,
@SerializedName("publishedAt") var publishedAt: String,
@SerializedName("source") var source: String,
@SerializedName("type") var type: String,
@SerializedName("url") var url: String,
@SerializedName("used") var used: Boolean,
@SerializedName("who") var who: String) : Parcelable {
companion object {
@JvmField val CREATOR: Parcelable.Creator<DataEntities> = object : Parcelable.Creator<DataEntities> {
override fun createFromParcel(source: Parcel): DataEntities = DataEntities(source)
override fun newArray(size: Int): Array<DataEntities?> = arrayOfNulls(size)
}
}
constructor(source: Parcel) : this(
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
source.readString(),
1 == source.readInt(),
source.readString()
)
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(_id)
dest.writeString(createdAt)
dest.writeString(desc)
dest.writeString(publishedAt)
dest.writeString(source)
dest.writeString(type)
dest.writeString(url)
dest.writeInt((if (used) 1 else 0))
dest.writeString(who)
}
}
/**
* Created by JokAr on 2017/6/5.
*/
data class HttpResult<T>(@SerializedName("error") var error: Boolean,
@SerializedName("results") var results: T?)
然后就是使用方法了
NetworkConfig.instance
.retrofit
.create(DataService::class.java)
.getData("Android", 10, 1)
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.io())
.map(HttpResultFunc())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
result ->
Log.d("Kotlin", result.toString())
}, {
error ->
error.printStackTrace()
}, {
Log.d("Kotlin", "onComplete")
}, {
Log.d("Kotlin", "onStart")
})
其中HttpResultFunc
为:
/**
* Created by JokAr on 2017/6/5.
*/
class HttpResultFunc<T> :Function<HttpResult<T>,T> {
override fun apply(tHttpResult: HttpResult<T>?): T {
if (tHttpResult != null) {
if (tHttpResult?.error) {
throw APIException()
}
}
return tHttpResult?.results as T
}
}
END
到此就结束了,跟在java中使用没多大区别,就只是在最后的subscribe
有点区别,在代码中已注明
作者:JokAr_
链接:https://www.jianshu.com/p/b39c0061a1a8
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。