Retrofit框架源码分析一
Retrofit基本使用
第一步:
//先引入依赖,(这里不需要另外引入OkHttp依赖,因为Retrofit默认内置)
//第一个,retrofit依赖
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
//第二个,用于GsonConverterFactory
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
//第三个,CallAdapterFactory用于RxJava,可以不引入
implementation 'com.squareup.retrofit2:adapter-rxjava:2.6.0'
//然后添加网络权限
<uses-permission android:name="android.permission.INTERNET"/>
第二步:新建服务器响应回来的实体类MyResponse
//请求接口为:http://api.nnzhp.cn/api/user/stu_info/
//响应内容为:{
// "error_code": 3001,
// "msg": "必填参数未填!请查看接口文档!"
//}
public class MyResponse {
/**
* error_code : 3001
* msg : 必填参数未填!请查看接口文档!
*/
private int error_code;
private String msg;
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
第三步:新建接口类MyInterface
//这里传入请求的路劲,以及响应实体类。
public interface MyInterface {
@GET("user/stu_info/")
Call<MyResponse> getCall();
}
第四步:发送请求,获取服务器数据
// url必须以 / 结尾,addCallAdapterFactory可以不添加。
Retrofit retrofit=new Retrofit.Builder()
.baseUrl("http://api.nnzhp.cn/api/")
//设置数据转换器Gson
.addConverterFactory(GsonConverterFactory.create())
//设置支持RxJava
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
MyInterface myInterface=retrofit.create(MyInterface.class);
Call<MyResponse> call=myInterface.getCall();
call.enqueue(new Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
Log.d("crook",response.body().getMsg());
}
@Override
public void onFailure(Call<MyResponse> call, Throwable t) {
}
});
//输出结果为:
//crook: 必填参数未填!请查看接口文档!
具体源码解析:
//new Retrofit.Builder()中的Builder()方法的实现,最终调用如下方法
//获取支持的平台,Android
private static Platform findPlatform() {
try {
//查找类名为android.os.Build的类,如果抛出异常,说明没有找到。
Class.forName("android.os.Build");
if (Build.VERSION.SDK_INT != 0) {
return new Android();
}
} catch (ClassNotFoundException ignored) {
}
}
// .baseUrl("http://api.nnzhp.cn/api/")方法的实现
public Builder baseUrl(String baseUrl) {
checkNotNull(baseUrl, "baseUrl == null");
//将String类型的url转换成HttpUrl类型
return baseUrl(HttpUrl.get(baseUrl));
}
//最终调用下面的baseUrl方法
public Builder baseUrl(HttpUrl baseUrl) {
List<String> pathSegments = baseUrl.pathSegments();
//baseurl必须以斜杠结尾
if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
}
return this;
}
//.addConverterFactory(GsonConverterFactory.create())方法的实现
public Builder addConverterFactory(Converter.Factory factory) {
//将factory添加至converterFactories集合
converterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
// GsonConverterFactory.create()方法的实现
public static GsonConverterFactory create(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
//new Gson然后传入
return new GsonConverterFactory(gson);
}
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())方法的实现
public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
//将数据适配器工厂添加至集合
callAdapterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
// .build()方法的实现
// 将前面创建的对象,以及创建的默认对象,传入new Retrofit()的构造方法
public Retrofit build() {
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
}
Retrofit是封装了OkHttp的RESTFUL风格的网络请求框架,通过动态代理将Java接口转换成HTTP请求。所以,如果想弄清楚原理,首先要理解代理模式,尤其是动态代理。
静态代理
//新建一个接口Subject
public interface Subject {
public void myFunc(String arg);
}
//新建一个目标类,并实现接口Subject
public class RealSubject implements Subject {
@Override
public void myFunc(String arg) {
System.out.println("RealSubject:"+arg);
}
}
//新建一个代理类,并调用目标类
public class SubjectProxy implements Subject {
private RealSubject realProxy = new RealSubject();
@Override
public void myFunc(String arg) {
realProxy.myFunc(arg);
}
}
//测试静态代理的类
public class MyClass {
public static void main(String [] a){
SubjectProxy subjectProxy=new SubjectProxy();
subjectProxy.myFunc("静态代理");
}
}
//测试结果:
RealSubject:静态代理
动态代理:
//新建动态代理类
public class ProxyHandler implements InvocationHandler {
private Object mTarget;
public Object bind(Object target){
mTarget=target;
return Proxy.newProxyInstance(mTarget.getClass().getClassLoader(),
mTarget.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
Object result=null;
System.out.println("动态代理:方法调用之前");
result=method.invoke(mTarget,objects);
System.out.println("动态代理:方法调用之后");
return result;
}
}
//测试类
public static void main(String [] a){
ProxyHandler proxyHandler=new ProxyHandler();
//传入目标类RealSubject
Subject subject= (Subject) proxyHandler.bind(new RealSubject());
subject.myFunc("动态代理");
}
}
//测试结果
动态代理:方法调用之前
RealSubject:动态代理
动态代理:方法调用之后
// MyInterface myInterface=retrofit.create(MyInterface.class)
//中create()方法的实现
public <T> T create(final Class<T> service) {
//动态代理
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
@Override public @Nullable Object invoke(Object proxy, Method method,
@Nullable Object[] args) throws Throwable {
//返回ServiceMethod
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}
//loadServiceMethod()方法的实现
ServiceMethod<?> loadServiceMethod(Method method) {
//从serviceMethodCache集合中获取,如果没有获取到,则重新创建
ServiceMethod<?> result = serviceMethodCache.get(method);
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//没有获取到serviceMethod,则重新创建并存放serviceMethodCache集合作为缓存。
result = ServiceMethod.parseAnnotations(this, method);
serviceMethodCache.put(method, result);
}
}
return result;
}
//ServiceMethod.parseAnnotations(this, method)方法的实现
static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
Type returnType = method.getGenericReturnType();
//继续调用
return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
}
//HttpServiceMethod.parseAnnotations()方法的实现
static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
Retrofit retrofit, Method method, RequestFactory requestFactory) {
//首先创建CallAdapter
CallAdapter<ResponseT, ReturnT> callAdapter =
createCallAdapter(retrofit, method, adapterType, annotations);
//然后创建数据转换器
Converter<ResponseBody, ResponseT> responseConverter =
createResponseConverter(retrofit, method, responseType);
}
//createCallAdapter()方法最终调用nextCallAdapter()方法
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
int start = callAdapterFactories.indexOf(skipPast) + 1;
//从集合callAdapterFactories中获取CallAdapter
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
}