-
首先gradle种导入第三方库,由于Retrofit是基于OKHttp3的所以也要导入ok的库
//Retrofit本体 implementation 'com.squareup.retrofit2:retrofit:2.4.0' //OkHttp implementation 'com.squareup.okhttp3:okhttp:3.11.0' //OkHttp依赖的okio implementation 'com.squareup.okio:okio:1.15.0' //Retrofit Gson转换器 implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
-
创建API接口服务
详情可以参考这里public interface ApiService { @GET("category-list") Call<AppCategoryBean> getCategory(); @GET("category") Call<AppCategoryDetailBean> getCategoryDetail(@Query("id") int id); @GET("info") Call<AppDetailBean> getAppdetail(@Query("appid") int appid); }
-
创建retrofit实例
val BASE_URL = "http://www.baidu.com/" //直以base url 要已/为结尾. var retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build()
-
创建Api接口实例
val service = retrofit.create(ApiService::class.java)
-
访问网络
val call = service.category call.enqueue(object : Callback<AppCategoryBean> { override fun onFailure(call: Call<AppCategoryBean>, t: Throwable) { //失败的回调 } override fun onResponse(call: Call<AppCategoryBean>, response: Response<AppCategoryBean>) { //成功的回调 } })
网友评论