之前网络方面一直用的是Volley,但是近期发现Retrofit和Rxjava越来越火,抽时间学习了一下他们。
在此记录一下使用过程(分别从单纯利用Retrofit网络连接,以及Retrofit和Rxjava结合的请求)
(一)单独利用Retrofit 进行网络请求。
首先放上build.gradle的依赖
compile 'com.google.code.gson:gson:2.7' //rxjava compile 'com.squareup.retrofit2:retrofit-converters:2.1.0' compile 'com.squareup.retrofit2:converter-gson:2.1.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0' compile 'com.squareup.retrofit2:retrofit:2.1.0' compile 'com.squareup.retrofit2:converter-scalars:2.1.0' compile 'com.github.bumptech.glide:glide:3.7.0' compile 'io.reactivex:rxandroid:1.2.1'在测试用例中用的是豆瓣的一个电影信息连接
https://api.douban.com/v2/movie/top250?start=0&count=10
返回格式请自行查看。
(1)既然我们要请求数据,第一步肯定得有一个实体类:Movie
public class Movie { public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAlt() { return alt; } public void setAlt(String alt) { this.alt = alt; } String title; String alt; }(2)我们编写一个请求接口ApiService
public interface ApiService { @GET("top250") Call<Movie> getMovieInfo(@Query("start")int start, @Query("count") int count); }
解释:这里使用了注解
@GET 表示进行Get请求
@Query代表参数名 后面紧跟他的值
完整的请求就是 ......./top250?start=0&count=100
(3)准备工作完成,开始进行网络请求
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.douban.com/v2/movie/") .addConverterFactory(GsonConverterFactory.create())//添加 json 转换器 .build(); ApiService apiService = retrofit.create(ApiService.class);//这里采用的是Java的动态代理模式 Call<Movie> call=apiService.getMovieInfo(0,10); call.enqueue(new Callback<Movie>() { @Override public void onResponse(Call<Movie> call, Response<Movie> response) { //do Something } @Override public void onFailure(Call<Movie> call, Throwable t) { //do Something } });