一、Retrofit简介
Retrofit是当下最热门的Android网络请求库,
它内部网络请求的工作,本质上是通过OkHttp完成,而Retrofit仅负责网络请求接口的封装。
效率高,实现简单,运用注解和动态代理.。
二、Retrofit的使用
使用步骤
1、创建业务请求接口
public interface MoviceService {
@GET("movie/top250")
Call<MovieBean> getTop250(@Query("start") int start,@Query("count") int count);
}
2、创建一个Retrofit实例
public static final String BASE_URL ="https://api.douban.com/v2/";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
3、获取接口实例对象
MoviceService moviceService = retrofit.create(MoviceService.class);
4、调用方法,获取一个Call的实例
Call<MovieBean> call= moviceService.getTop250(0, 20);
5、使用Call的实例完成请求
//同步请求
MovieBean movieBean= call.execute().body();
//异步请求
call.enqueue(new Callback<MovieBean>() {
@Override
public void onResponse(Call<MovieBean> call, Response<MovieBean> response) {
//成功 do something
MovieBean movieBean = response.body();
}
@Override
public void onFailure(Call<MovieBean> call, Throwable t) {
//失败
}
});
参考链接 https://blog.youkuaiyun.com/suyimin2010/article/details/91351636
https://www.jianshu.com/p/0f32494a4c46