- 简介
- 主要流程
- 依赖包
- 具体实现
- 处理复杂接口地址类型
1.简介
Retrofit是使用接口动态生成实现类,在接口上定义了 请求方式、路径、参数等注解,Retrofit可以方便地从注解中获取这些参数,然后通过OkHttp访问网络
2.主要流程
3.依赖包
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'//Gson解析
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'//Rxjava
4.具体实现
(1)创建Api接口
定义请求方式、请求子路径、请求参数等
返回的是一个Call对象
(2)构建Retrofit单例实例
public class RetrofitClient {
private static final String ROOT_UTL = "http://music.eleuu.com/";
//单例模式
private static volatile RetrofitClient instance;
private RetrofitClient(){}
public static RetrofitClient getInstance() {
if (instance == null) {
synchronized (RetrofitClient.class) {
if (instance == null) {
instance = new RetrofitClient();
}
}
}
return instance;
}
// OKHttp客户端
OkHttpClient.Builder httpBuilder = new OkHttpClient.Builder();
// 各种参数配置
OkHttpClient okHttpClient = httpBuilder
.addNetworkInterceptor(new StethoInterceptor())
.readTimeout(10000, TimeUnit.SECONDS)
.connectTimeout(10000, TimeUnit.SECONDS)
.writeTimeout(10000, TimeUnit.SECONDS)
.build();
//配置
private final Retrofit retrofit = new Retrofit.Builder()
//设置根地址
.baseUrl(ROOT_UTL)
// TODO 请求用 OKhttp
.client(okHttpClient)
//设置数据解析器 -> 用Gson解析
.addConverterFactory(GsonConverterFactory.create())
// 添加rxjava处理工具
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
//返回一个接口对象 --- 泛型 针对不同的Service接口传入相应的Class对象
public <T> T create(Class<T> serviceClass){
//将接口转换为实现类
return retrofit.create(serviceClass);
}
}
1)用RetrofitUtils工具类封装
2)创建Retrofit单例实例
3)配置Retrofit实例,设置根地址、解析器
4)用Retrofit实例将Api接口转换为实例
5)得到一个Call对象,用Call对象访问网络
(3)调用Cal对象访问网络
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AppService appService = RetrofitUtils.getInstance().create(AppService.class);
appService.getDataByids("347601").enqueue(new Callback<JsonRootBean>() {
@Override
public void onResponse(Call<JsonRootBean> call, Response<JsonRootBean> response) {
JsonRootBean s = response.body();
Log.d("jiang", String.valueOf(s.getSongs()));
}
@Override
public void onFailure(Call<JsonRootBean> call, Throwable t) {
}
});
}
});
5.处理复杂接口地址类型
(1)对于分页api接口
例如:
http://example.com/<page>/get_data.json
//分页
@GET("{page}/get_data.json")
Call<JsonRootBean> getJsonRootBeanByPage(@Path("page")int page);
@GET()中 -> {page}用{}将需要替换的参数包围起来
@Path()中 -> 指定要替换子路径的参数名
(2)对于要求传入参数
例如:
http://expamle.com/get_data.json?u=<user>&t=<token>
@GET("get_data.json")
Call<JsonRootBean> getJsonRootBeanByPageByUserAndToken(@Query("u") String user,@Query("t") String token);
用Query()注解 -> 指定子路径中的参数