Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装。
网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装
App应用程序通过 Retrofit 请求网络,实际上是使用 Retrofit 接口层封装请求参数、Header、Url 等信息,之后由 OkHttp 完成后续的请求操作
在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,Retrofit根据用户的需求对结果进行解析
网络请求框架对比
asyncHttp:基于HttpClient 异步请求 ,匿名回调中处理结果,android5.0后不推荐使用
volley: 基于HttpUrlClient : 封装了图片加载框架,网络请求优先级处理, activity 与生命周期联动, 应用简单,适用于轻量级操作,网络传递数据小,(不适用于上传文件 : volley的request 和reoponse都是把数据放到byte数组里,不支持输入输出流,因此大量数据就会严重消耗内存,所以不适合上传文件操作 )
okhttp 高性能的请求框架, 可以理解为封装好的HttpUrlConnection, 支持同步异步,封装了线程池, 适用于重量级的网络请求,传数据量大,
retrofit: 基于okhttp , restful风格 ,支持同步异步,通过注解进行配置, 包括请求方法,请求参数,请求头,返回值等.提供 gson rxjava 支持
Retrofit 使用
先创建接口,注解申明、请求方式Post/Get等
public interface Service {
Observable<LoginBean> getLogin(@Query("no") String no,
@Query("password") String password);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.build();
Service service = retrofit.create(Service.class);
Call<LoginBean> userCall = service.getLogin(no ,password);
userCall.enqueue(new Callback<LoginBean>() {
@Override
public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
}
@Override
public void onFailure(Call<LoginBean> call, Throwable t) {
}
});
Retrofit跟OkHttp一样,都是采用了builder设计模式,在Builder构造方法中初始化了Platform,用来判断是在哪个平台运行来初始化不同的线程池。
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
baseUrl 判断是否为null,接下来设置callFactory,这个是我们在初始化Retrofit时通过callFactory()方法传进去,如果没有传的话,Retrofit则直接创建OkHttpClient,接下来就是设置回调线程,同理也是我们初始化时通过callbackExecutor()方法传进去,如果没有传的话Retrofit会通过PlatForm给我们创建。
/**
* Create the {@link Retrofit} instance using the configured values.
* <p>
* Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link
* OkHttpClient} will be created and used.
*/
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
说完 Retrofit的初始化,接下来我们来看看它的create方法。
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);
}
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
@Override public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
loadServiceMethod()方法查询是否有缓存,有的话直接使用缓存的ServiceMethod,没有则创建一个并把它添加到serviceMethodCache中
ServiceMethod<?, ?> loadServiceMethod(Method method) {
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
result = new ServiceMethod.Builder<>(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
作者:grpc
来源:CSDN
原文:https://blog.csdn.net/qq_36261644/article/details/88650521
版权声明:本文为博主原创文章,转载请附上博文链接!