1,加入网络访问权限
<uses-permission android:name="android.permission.INTERNET" />
2,引入依赖
implementation "com.google.code.gson:gson:2.8.5" implementation "com.squareup.retrofit2:retrofit:2.9.0" implementation "com.squareup.retrofit2:converter-gson:2.9.0"
3,实体类
data class Banner( val desc: String, val id: Int, val imagePath: String, val isVisible: Int, val order: Int, val title: String, val type: Int, val url: String )
4,模板返回体
data class BaseResponse<T>( val data: T, val errorCode: Int, val errorMsg: String )
5,API类
import retrofit2.Call import retrofit2.http.GET interface WanAndroidApi { @GET("banner/json") fun getBanners(): Call<BaseResponse<List<Banner>>> }
6,工具类
import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object NetworkUtil { private val retrofit: Retrofit = Retrofit.Builder() .baseUrl("https://www.wanandroid.com/") .addConverterFactory(GsonConverterFactory.create()) .build() val wanAndroidApi:WanAndroidApi = retrofit.create(WanAndroidApi::class.java) }