retrofit封装了okhttp,采用注解的模式来实现网络请求,目前来说,是最好用的网络框架之一。
首先引入依赖
implementation 'com.squareup.retrofit2:retrofit:2.5.0'//Retrofit依赖
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'//可选依赖,解析json字符所用
implementation 'com.squareup.retrofit2:converter-scalars:2.0.0' //解析字符串
开启网络权限
<uses-permission android:name="android.permission.INTERNET"/>
设置一个代理api
interface MyService {
@GET("/")
fun getApp() : Call<String>
}
值得注意的是注解里面的参数,如果有数据就要填写数据,如果没有数据,就用“.”或“/”来标记,不能写成@GET或@GET("")否则会报 java.lang.IllegalArgumentException: Missing either @GET URL or @Url parameter.
我们现在可以来写网络请求了
//1.获取retrofit实例
val retorfit = Retrofit.Builder()
.baseUrl("http