
retrofit将okhttp进行封装,使用注解将请求抽象成
接口
来使用。retrofit本身只是一个网络请求框架的封装
1.创建Retrofit并设置基本参数:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("baseurl")
//添加转化器
.addConverterFactory(GsonConverterFactory.create())
//添加rxjava支持
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
2.创建请求接口:
public interface retrofitService {
@GET("try")
public Call getCall();
}
这里填写的try
最终后baseurl拼接成完整的接口(baseurl+try)
3.通过创建出来的Retrofit获取网络请求接口:
retrofitService retrofitService = retrofit.create(retrofitService.class);
4.通过接口获取请求方法:
Call call = retrofitService.getCall();
5.进行网络请求:
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
完整代码:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("baseurl")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
retrofitService retrofitService = retrofit.create(retrofitService.class);
Call call = retrofitService.getCall();
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
总结:
retrofit的网络通信的8步骤:
- 创建Retrofit实例
- 创建网络请求接口并为接口中的方法添加
注解
- 通过动态代理生成网络请求对象
- 通过
网络请求适配器(addCallAdapterFactory)
进行网络请求对象进行平台适配 - 通过
网络请求执行球(Call)
发送网络请求 - 通过
数据转换器(addConverterFactory)
解析数据 - 通过
回调执行器
切换线程 - 用户在主线程处理服务器返回的数据
7个关键成员变量:
public final class Retrofit {
private final Map<Method, ServiceMethod<?, ?>> serviceMethodCache = new ConcurrentHashMap<>();
final okhttp3.Call.Factory callFactory;
final HttpUrl baseUrl;
final List<Converter.Factory> converterFactories;
final List<CallAdapter.Factory> adapterFactories;
final @Nullable Executor callbackExecutor;
final boolean validateEagerly;
...
-
serviceMethodCache
缓存网络请求。Method
请求方法,ServiceMethod
解析注解后的请求方法。 -
callFactory
请求网络的okhttp工厂 -
baseUrl
url请求基地址 -
converterFactories
数据转化器集合 -
adapterFactories
网络请求适配器集合(主要用于将call对象请求转化成我们需要的其他类型请求,比如rxjava的Observable) -
callbackExecutor
用于执行异步回调的 -
validateEagerly
标志位表示是否需要立即解析接口中的方法
网友评论