依赖
implementation'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
implementation'com.squareup.retrofit2:converter-gson:2.9.0'
简单使用
接口
@GET("url")
fun getEvent(@Query("id") info:String):Call<EventBean>
开始请求
var retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constant.iP)
.client(client)
.build()
.create(RetrofitInterface::class.java);
retrofit.enqueue(object:retrofit2.Callback<EventBean>{
override fun onFailure(call: Call<EventBean>, t: Throwable) {
LogUtil.e(t.message)
}
override fun onResponse(call: Call<EventBean>, response: Response<EventBean>) {
LogUtil.e(response.body()?.data?.objs.toString())
response.body()?.data?.objs?.let { adapter.addData(it) }
}
})
加上rxjava使用
//Rxjava 记得在gradle里面加
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxjava:2.1.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
接口
@GET("url")
fun getReportedEvent(@Query("id") info:String):Observable<EventBean>
开始请求
var retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(Constant.iP)
.build()
.create(RetrofitInterface::class.java);
retrofit.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object : Observer<EventBean> {
override fun onSubscribe(d: Disposable) {
}
override fun onNext(t: EventBean) {
LogUtil.e(Gson().toJson(t!!))
t?.data.objs?.let { adapter.addData(it) }
}
override fun onError(e: Throwable) {
}
override fun onComplete() {
}
})
加全局请求参数
class CommonInterceptor(
private val paramKey: String,
private val paramValue: String, private val token: String
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val orderRequest = chain.request()
val addQueryParameter = orderRequest.url().newBuilder()
.scheme(orderRequest.url().scheme())
.host(orderRequest.url().host())
.addQueryParameter(paramKey, paramValue)
val trueBuild = orderRequest.newBuilder()
trueBuild.header("Authorization", "Bearer " + token)
trueBuild.method(orderRequest.method(), orderRequest.body())
trueBuild.url(addQueryParameter.build())
trueBuild.build()
return chain.proceed(trueBuild.build())
}
}
val userInfo = getUserInfo(getMyBaseContext())
var commonInterceptor: CommonInterceptor? = null;
if (userInfo != null) {
commonInterceptor = CommonInterceptor("partyId", ""+userInfo.orgParty, userInfo.token)
}
val builder = OkHttpClient.Builder()
if (commonInterceptor != null) {
builder.addInterceptor(commonInterceptor)
}
val client = builder.build()
Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constant.iP)
.client(client)
.build()
.create(RetrofitInterface::class.java);