添加Retrofit依赖
compile 'com.squareup.retrofit2:retrofit:2.4.0'
指定使用Gson解析数据,并与Retrofit关联(如果使用到)
compile 'com.google.code.gson:gson:2.8.5'compile 'com.squareup.retrofit2:converter-gson:2.4.0'
使用步骤:
1.获取Builder对象,并使用builder对象配置基本参数
Retrofit.Builder builder = new Retrofit.Builder();
builder.baseUrl("http://192.168.8.106:8080/");
builder.addConverterFactory(GsonConverterFactory.create());
2.通过builder构建Retrofit对象
Retrofit retrofit = builder.build();
3.定义一个接口配置链接和参数(封装完整url地址和请求参数、指定请求方式(GET或者POST))
public interface ResponseService {
@GET(Constant.login)
Call<ResponseInfo> login(@Query("sellerId") Integer id);
}
4.通过retrofit对象获得第3步定义的接口服务对象
ResponseService responseService = retrofit.create(ResponseService.class);
5.使用接口服务对象(responseService)调用接口中的方法获得Call对象,最后使用Call对象执行请求
Call<ResponseInfo> call = responseService.login(1); call.enqueue(new Callback<ResponseInfo>() { @Override public void onResponse(Call<ResponseInfo> call, Response<ResponseInfo> response) { mMainActivity.success(); } @Override public void onFailure(Call<ResponseInfo> call, Throwable t) { mMainActivity.failed(); } }); }