使用步骤
1、Retrofit 开源库、OkHttp网络库、数据解析器集成、注册网络权限
依赖包导入
implementation 'com.squareup.retrofit2:retrofit:2.2.0'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
网络权限
<uses-permission android:name="android.permission.INTERNET"/>
2、创建接口设置请求类型与参数
新建 UserInfoModel 和 UserInfoService 接口
@Get("login")
public Call<UserInfoModel> login(@Query("username")String username, @Query("pwd")String pwd);
经常使用的注解参考以下链接:https://www.jianshu.com/p/f7026cbf1cc9
3、创建 Retrofit 对象、设置数据解析器
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
4、生成接口对象
UserMgrService service = retrofit.create(UserMgrService.class);
5、调用接口方法返回Call 对象
Call<UserInfoModel> call = service.login("Gene", "000000");
6、发送请求(同步、异步)
同步:调用 Call 对象的 execute(),返回结果的响应体
异步:调用 Call 对象的 enqueue(), 参数是一个回调
7、处理返回数据
实例