Retrofit网络请求框架要点总结
概述
Retrofit2是利用接口、方法和注解参数来声明定义请求的。
默认采用OkHttp(retrofit1.x中用的是Square包下的,retrofit2.0用的是okHttp3,两者api有较大不同)做请求代理,序列化没有默认需要自己定义。
可以同步发送请求,也可以异步发送请求 异步时候需要定义回调,同步时候需要处理异常。
缓存采用OkHttp自带缓存进行处理。
示例
网络权限
<uses-permission android:name="android.permission.INTERNET" />
使用retrofit1.x时gradle依赖库
dependencies {
compile 'com.google.code.gson:gson:2.3'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta1'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp:okhttp:2.4.0'
}
使用retrofit2.0时gradle依赖库
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
从retrofit2.0开始,在Retrofit包中将不包含Converter,所以需要手动的插入一个转换器在Retrofit中,否则只能接受String结果,所以Retrofit2.0不再依赖Gson。
以下是基于Retrofit2.0的讲解
定义数据模型
public class ArticlesModel {
.....
}
定义接口
/**
* 爱卡汽车app首页请求接口
* http://a.xcar.com.cn/interface/6.0/newsList.php/*type=1&provinceId=xxx&cityId=xxx&offset=xxx&limit=xx*x&ver=xxx
*/
interface MainHttpServer{
//设置头信息 保存缓存
@Headers("Cache-Control: public, max-age=604800 ,max-stale=2419200")
// maxAge max-stale感觉两个类类似 都是设置最大失效时间,失效则不使用 需要服务器配合
//get请求
@GET("newsList.php")
Call<ArticlesModel> requestArticles(
@Query("type") String type,
@Query("provinceId") String provinceId,
@Query("cityId") String cityId,
@Query("offset") String offset,
@Query("limit") String limit,
@Query("ver") String ver
);
}
初始化Retrofit
//初