.build();
说明:配置了接口的baseUrl和一个converter,GsonConverterFactory 是默认提供的Gson 转换器,Retrofit 也支持其他的一些转换器,详情请看官网Retrofit官网
3,创建一个 接口 ,代码如下:
public interface MovieService {
//获取豆瓣Top250 榜单
@GET(“top250”)
Call getTop250(@Query(“start”) int start,@Query(“count”)int count);
}
说明:定义了一个方法getTop250,使用get请求方式,加上@GET 标签,标签后面是这个接口的 尾址top250,完整的地址应该是 baseUrl+尾址 ,参数 使用@Query标签,如果参数多的话可以用@QueryMap标签,接收一个Map
4,用Retrofit 创建 接口实例 MoiveService,并且调用接口中的方法进行网络请求,代码如下:
//获取接口实例
MovieService MovieService movieService = retrofit.create(MovieService.class);
//调用方法得到一个Call
Call call = movieService.getTop250(0,20);
//进行网络请求
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
mMovieAdapter.setMovies(response.body().subjects);
mMovieAdapter.notifyDataSetChanged();
}
@Override
public void onFailure(Call call, Throwable t) {
t.printStackTrace();
}
});
以上是异步方式请求,还有同步方式execute(),返回一个Response,代码如下:
Response response = call.execute();
以上就是用Retrofit 完成了一个网络请求,获取豆瓣top250 榜单电影,效果图如下: