Retrofit2.0 学习小记
来自官网的介绍:Retrofit turns your HTTP API into Java interface.Retrofit把HTTP API变成Java的接口。
1.基本用法
直接上代码:比如我们使用豆瓣电影的Top250做测试链接,目标地址为:https://api.douban.com/v2/movie/top250?start=0&count=10
导包:compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
首先要建这样一个接口:
public interface MovieService{
@GET("top250")
Call<MovieEntity> getTopMovie(@Query("start")int start,@Query("count") int count);
}
然后你还需要创建一个Retrofit对象:
public static final String baseUrl="https://api.douban.com/v2/movie/";
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
再用这个Retrofit对象创建一个MovieService对象:
MovieService movieService=retrofit.create(MovieService.class);
Call<MovieEntity> call=movieService.getTopMovie(0,10);
//call.enqueue()异步请求,call.execute()同步请求
call.enqueue(new Callback<MovieEntity>(){
@Override
public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
result_TV.setText(response.body().toString());
}
@Override
public void onFailure(Call<MovieEntity> call, Throwable t) {
result_TV.setText(t.getMessage());
}
});
在这边还可以移除一个请求:
Retrofit 1.x版本没有直接取消正在进行中任务的方法的,在2.x的版本中,Service的模式变成Call的形式的原因是为了让正在进行的事务可以被取消。要做到这点,只需要调用call.cancel()。
以上就是Retrofit2.0的基本用法了,下面讲讲它的详细用法:
1.关于各种网络请求的service
下面分为GET、POST、DELETE和PUT的请求,说明@Path、@Query、@QueryMap、@Body、@Filed的用法。
GET
1.一个简单的get请求:
http://102.10.10.132/api/News
@GET("News") Call<NewsBean> getItem();
2.URL中带有参数:http://102.10.10.132/api/News/{资讯id}
@GET("News/{newsId}")
Call<NewsBean> getItem(@Path("newsId") String newsId);
3.参数在URL问号之后:http://102.10.10.132/api/News?newsId={资讯id}
@GET("News")
Call<NewsBean> getItem(@Query("newsId") String newsId);
或者带有两个参数:http://102.10.10.132/api/News?newsId={资讯id}&type={类型}
@GET("News")
Call<NewsBean> getItem(@Query("newsId") String newsId,@Query("type") type);
4.多个参数在URL问号之后,且个数不确定:
http://102.10.10.132/api/News?newsId={资讯id}&type={类型}...
@GET("News")
Call<NewsBean> getItem(@QueryMap Map<String, String> map);
POST
1.需要补全URL,post的数据只有一条reason:
http://102.10.10.132/api/Comments/{newsId}
@FormUrlEncoded
@POST("Comments/{newsId}")
Call<Comment> reportComment(@Path("newsId") String commentId,@Field("reason") String reason);
2.需要补全URL,问号后加入access_token,post的数据只有一条reason:
http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}
@FormUrlEncoded
@POST("Comment/{newsId}")
Call<Comment> reportComment(@Path("newsId") String commentId,@Query("access_token") String access_token,@Field("reason") String reason);
3.需要补全URL,问号后加入access_token,post一个body(对象):
http://102.10.10.132/api/Comments/{newsId}?access_token={access_token}
@FormUrlEncoded
@POST("Comment/{newsId}")
Call<Comment> reportComment(@Path("newsId") String commentId,@Query("access_token") String access_token,@Body CommentBean bean);
关于DELETE和PUT方式由于使用较少,这里就不举例了,可自行google
总结:
@Path:URL问号之前的参数
@Query:URL问号后面的参数
@QueryMap:相当于多个@Query
@Field:用于POST请求,提交单个数据
@Body:相当于多个@Field,以对象的形式提交
若需要重新定义接口地址,可以使用@Url,例如:
@GET
Call<MovieEntity> getTopMovie(@Url String url,@Query("start")int start,@Query("count") int count);
关于解析
在Retrofit2.0中,Converter不再包含在packeage中了,需要自己添加Converter,不然的话Retrofit只能接收字符串结果。同样的,Retrofit也不再依赖于Gson,如果你想接收json结果并解析成DAO,你必须把GsonConverter作为一个独立的依赖添加进来:compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2' ,然后使用addConverterFactory(GsonConverterFactory.create())帮他添加进来。
官方Converter modules列表
Gson: com.squareup.retrofit:converter-gson
Jackson: com.squareup.retrofit:converter-jackson
Moshi: com.squareup.retrofit:converter-moshi
Protobuf:com.squareup.retrofit:converter-protobuf
Wire: com.squareup.retrofit:converter-wire
Simple XML: com.squareup.retrofit:converter-simplexml
当然也可以通过实现Converter.Factory接口来创建一个自定义的converter。
2.Retrofit+RxJava(附上demo)
导包:
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
compile 'io.reactivex:rxandroid:1.1.0'
在创建Retrofit的过程添加以下代码:
Retrofit retrofit=new Retrofit.Builder()
.baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create())
//结合RxJava .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
这样一来我们定义的Service返回值就不再是一个Call了,而是一个Observable,重新定义MovieService:
public interface MovieService {
@GET("top250")
Observable<MovieEntity> getTopMovie(@Query("start") int start, @Query("count") int count);
}
在网络请求方法中改为:
//进行网络请求
private void getMovie(){
Retrofit retrofit = <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">new</span></span> Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
MovieService movieService = retrofit.create(MovieService.class);
movieService.getTopMovie(<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-number"</span>><span class="hljs-number">0</span></span>, <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-number"</span>><span class="hljs-number">10</span></span>)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">new</span></span> Subscriber<MovieEntity>() {
<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-annotation"</span>>@Override</span>
<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-function"</span>><span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">public</span></span> <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">void</span></span> <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-title"</span>>onCompleted</span><span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-params"</span>>()</span> </span>{
Toast.makeText(MainActivity.<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">this</span></span>, <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-string"</span>><span class="hljs-string">"Get Top Movie Completed"</span></span>, Toast.LENGTH_SHORT).show();
}
<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-annotation"</span>>@Override</span>
<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-function"</span>><span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">public</span></span> <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">void</span></span> <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-title"</span>>onError</span><span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-params"</span>>(Throwable e)</span> </span>{
resultTV.setText(e.getMessage());
}
<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-annotation"</span>>@Override</span>
<span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-function"</span>><span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">public</span></span> <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-keyword"</span>><span class="hljs-keyword">void</span></span> <span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-title"</span>>onNext</span><span <span class="hljs-keyword">class</span>=<span class="hljs-string">"hljs-params"</span>>(MovieEntity movieEntity)</span> </span>{
resultTV.setText(movieEntity.toString());
}
});
}
这就基本上完成了Retrofit和RxJava的结合,但是可以把创建Retrofit的过程封装一下。可参考这篇文章,不错的一个例子