您的位置:首页 > 理论基础 > 计算机网络

Retrofit+Rxjava+OkHttp

2016-11-22 00:00 246 查看
摘要: 各自的职责:Retrofit 负责请求的数据和请求的结果,使用接口的方式呈现,OkHttp 负责请求的过程,RxJava 负责异步,各种线程之间的切换。

参考:

http://duanyytop.github.io/2016/08/06/Retrofit%E7%94%A8%E6%B3%95%E8%AF%A6%E8%A7%A3/

http://www.jianshu.com/p/811ba49d0748

1,首先,要使用Retrofit ,你肯定需要把它的包引入,在你的build.gradle文件中添加如下配置:

compile 'com.squareup.retrofit2:retrofit:2.1.0'//retrofit
compile 'com.google.code.gson:gson:2.6.2'//Gson 库
//下面两个是RxJava 和RxAndroid
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'//转换器,请求结果转换成Model
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'//配合Rxjava 使用

说明:使用POST 请求方式时,只需要更改方法定义的标签,用@POST 标签,参数标签用 @Field 或者@Body或者FieldMap,注意:使用POST 方式时注意2点,1,必须加上 @FormUrlEncoded标签,否则会抛异常。2,使用POST方式时,必须要有参数,否则会抛异常:

if (isFormEncoded && !gotField) {
throw methodError("Form-encoded method must contain at least one @Field.");
}

接口实例 post/get:

//post接口:
public interface MovieService {
//获取豆瓣Top250 榜单
@FormUrlEncoded
@POST("top250")
Call<MovieSubject> getTop250(@Field("start") int start, @Field("count") int count);
}
//get接口:
public interface MovieService {

//获取豆瓣Top250 榜单
@GET("top250")
Call<MovieSubject> getTop250(@Query("start") int start,@Query("count")int count);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: