Retrofit分析

Retrofit分析(网络封装框架–>解耦)

需要关注的第一个点就是:create(Class service)

public <T> T create(final Class<T> service) {
	//检查是否是接口
    validateServiceInterface(service);
	//开始动态代理
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          private final Platform platform = Platform.get();
          private final Object[] emptyArgs = new Object[0];

          @Override public @Nullable Object invoke(Object proxy, Method method,
              @Nullable 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);
            }
			//Retrofit的功能入口点
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
  }

loadServiceMethod(method).invoke(args != null ? args : emptyArgs);先看前半截的loadServiceMethod():

//返回的是ServiceMethod	
  ServiceMethod<?> loadServiceMethod(Method method) {
	//缓存  Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
	// 使用的是 ConcurrentHashMap,
    ServiceMethod<?> result = serviceMethodCache.get(method);
    if (result != null) return result;
	//对象锁加持
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
		//解析方法
        result = ServiceMethod.parseAnnotations(this, method);
		//放入map
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

ServiceMethod.parseAnnotations

  // ServiceMethod.java
  static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
	###解析注解###
    RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
	//解析返回类型
    Type returnType = method.getGenericReturnType();
    if (Utils.hasUnresolvableType(returnType)) {
      throw methodError(method,
          "Method return type must not include a type variable or wildcard: %s", returnType);
    }
    if (returnType == void.class) {
      throw methodError(method, "Service methods cannot return void.");
    }
 //带上解析出来的RequestFactory走进另一个类HttpServiceMethod
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
  }

RequestFactory.parseAnnotations解析注解

 //builder设计模式
  static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
    return new Builder(retrofit, method).build();
  }

  Builder(Retrofit retrofit, Method method) {
  this.retrofit = retrofit;
  this.method = method;
  //解析注解
  this.methodAnnotations = method.getAnnotations();
  this.parameterTypes = method.getGenericParameterTypes();
  this.parameterAnnotationsArray = method.getParameterAnnotations();
}
**看build()方法
RequestFactory build() {
 //for循环注解,看来是要验证注解的正确性,比如你写了一个@Post(""),括号内的url是否正确
  for (Annotation annotation : methodAnnotations) {
###AAA#### 解析各种请求,以及url.详情,请见下方AAA处
    parseMethodAnnotation(annotation);
  }
 ...
  return new RequestFactory(this);
}

AAA

//各种请求的验证
private void parseMethodAnnotation(Annotation annotation) {
  if (annotation instanceof DELETE) {
    parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
  } else if (annotation instanceof GET) {
    parseHttpMethodAndPath("GET", ((GET) annotation).value(), false);
  } else if (annotation instanceof HEAD) {
    parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false);
  } else if (annotation instanceof PATCH) {
    parseHttpMethodAndPath("PATCH", ((PATCH) annotation).value(), true);
  } else if (annotation instanceof POST) {
    parseHttpMethodAndPath("POST", ((POST) annotation).value(), true);
  } else if (annotation instanceof PUT) {
    parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true);
  } else if (annotation instanceof OPTIONS) {
    parseHttpMethodAndPath("OPTIONS", ((OPTIONS) annotation).value(), false);
  } else if (annotation instanceof HTTP) {
    HTTP http = (HTTP) annotation;
    parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
  } else if (annotation instanceof retrofit2.http.Headers) {
    String[] headersToParse = ((retrofit2.http.Headers) annotation).value();
    if (headersToParse.length == 0) {
      throw methodError(method, "@Headers annotation is empty.");
    }
    headers = parseHeaders(headersToParse);
  } else if (annotation instanceof Multipart) {
    if (isFormEncoded) {
      throw methodError(method, "Only one encoding annotation is allowed.");
    }
    isMultipart = true;
  } else if (annotation instanceof FormUrlEncoded) {
    if (isMultipart) {
      throw methodError(method, "Only one encoding annotation is allowed.");
    }
    isFormEncoded = true;
  }
} 

private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
//一个请求就只能有一种方法 如@POST,@GET
  if (this.httpMethod != null) {
    throw methodError(method, "Only one HTTP method is allowed. Found: %s and %s.",
        this.httpMethod, httpMethod);
  }
  this.httpMethod = httpMethod;
  this.hasBody = hasBody;

  if (value.isEmpty()) {
    return;
  }

  // Get the relative URL path and existing query string, if present.
  int question = value.indexOf('?');
  if (question != -1 && question < value.length() - 1) {
    // Ensure the query string does not have any named parameters.
    String queryParams = value.substring(question + 1);
    Matcher queryParamMatcher = PARAM_URL_REGEX.matcher(queryParams);
    if (queryParamMatcher.find()) {
      throw methodError(method, "URL query string \"%s\" must not have replace block. "
          + "For dynamic query parameters use @Query.", queryParams);
    }
  }
 //相对url地址
  this.relativeUrl = value;
 //返回一个路径,表示需要替换的参数
  this.relativeUrlParamNames = parsePathParameters(value);
}

回到ServiceMethod中:HttpServiceMethod.parseAnnotations (HttpServiceMethod继承自ServiceMethod)

static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
  Retrofit retrofit, Method method, RequestFactory requestFactory) {
//是否支持kotlin的协程.默认时false
boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
boolean continuationWantsResponse = false;
boolean continuationBodyNullable = false;

Annotation[] annotations = method.getAnnotations();
Type adapterType;
if (isKotlinSuspendFunction) {
	...
} else {
  adapterType = method.getGenericReturnType();
}
//这个CallAdapter就大有来头了,需要深入分析一下
###BBB###
CallAdapter<ResponseT, ReturnT> callAdapter =
    createCallAdapter(retrofit, method, adapterType, annotations);
Type responseType = callAdapter.responseType();
//检查返回的类型是否符合要求
if (responseType == okhttp3.Response.class) {
  throw methodError(method, "'"
      + getRawType(responseType).getName()
      + "' is not a valid response body type. Did you mean ResponseBody?");
}
if (responseType == Response.class) {
  throw methodError(method, "Response must include generic type (e.g., Response<String>)");
}
// TODO support Unit for Kotlin?
if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
  throw methodError(method, "HEAD method must use Void as response type.");
}

Converter<ResponseBody, ResponseT> responseConverter =
    createResponseConverter(retrofit, method, responseType);

okhttp3.Call.Factory callFactory = retrofit.callFactory;
if (!isKotlinSuspendFunction) {
	//默认情况下都是走这 ,CallAdapted继承自HttpServiceMethod
	//###CCC###
  return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
} else if (continuationWantsResponse) {
  //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
  return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForResponse<>(requestFactory,
      callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
} else {
  //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
  return (HttpServiceMethod<ResponseT, ReturnT>) new SuspendForBody<>(requestFactory,
      callFactory, responseConverter, (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
      continuationBodyNullable);
}}

BBB$createCallAdapter

  private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
      Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
	  //调用retrofit的callAdapter
      return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);}
##callAdapter --> nextCallAdapter
public CallAdapter<?, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
  Annotation[] annotations) {
//可以看出来寻找这个callAdapter要从callAdapterFactories这个集合中去寻找
//那么这个集合是在哪里初始化的了?
//细心的你应该已经发现,就是在Retrofit的内部类Build中完成了初始化
int start = callAdapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
  CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
  if (adapter != null) {
    return adapter;
  }
}

Retrofit$Build

Builder(Platform platform) {
  this.platform = platform;
}
public Builder() {
//Platform的get方法
  this(Platform.get());
}

class Platform {
 //PlatForm是一个单例设计模式
  private static final Platform PLATFORM = findPlatform();

  static Platform get() {
    return PLATFORM;
  }

  private static Platform findPlatform() {
    try {
      Class.forName("android.os.Build");
	//SDK的版本,当然不会为0
      if (Build.VERSION.SDK_INT != 0) {
	//看到这里new了一个Android类,其实这个Android类又继承自Platform
        return new Android();
      }
    } catch (ClassNotFoundException ignored) {
    }
    return new Platform(true);
  }

  static final class Android extends Platform {
    Android() {
      super(Build.VERSION.SDK_INT >= 24);
    }

    @Override public Executor defaultCallbackExecutor() {
      return new MainThreadExecutor();
    }
   // 一个Executor
    static class MainThreadExecutor implements Executor {
	// 可以看到这是一个Handler拿了主线程的Looper
      private final Handler handler = new Handler(Looper.getMainLooper());
      @Override public void execute(Runnable r) {
		//也就是调用这个execute,一会儿传进来的runable,回去执行的时候就在主线程了。
		//那么什么时候需要切换到主线程了,当然是使用okhttpClient的enqueue
        handler.post(r);}}}

通过上面的Platform分析,我们知道,一会儿调用defaultCallbackExecutor,会拿到一个Executor,执行executor(runbale)用来完成切换到主线程

public Retrofit build() {
  if (baseUrl == null) {
    throw new IllegalStateException("Base URL required.");
  }

  okhttp3.Call.Factory callFactory = this.callFactory;
  if (callFactory == null) {
	//如果没有传入OkhttpClient,那么直接创建一个OkhttpClient
    callFactory = new OkHttpClient();
  }

  Executor callbackExecutor = this.callbackExecutor;
  if (callbackExecutor == null) {
	//如上所分析,这拿到这个executor,就是切换到主线程的executor
    callbackExecutor = platform.defaultCallbackExecutor();
  }
  // Make a defensive copy of the adapters and add the default Call adapter.
  List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
  //这来了一次装饰,把这个executor封装到了CallAdapter.Factory
  callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));

platform.defaultCallAdapterFactories(callbackExecutor)

  List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
      @Nullable Executor callbackExecutor) {
	//创建了一个 DefaultCallAdapterFactory
    DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor);
    return hasJava8Types
        ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
        : singletonList(executorFactory);}

DefaultCallAdapterFactory

final class DefaultCallAdapterFactory extends CallAdapter.Factory {
  private final @Nullable Executor callbackExecutor;

  DefaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
    this.callbackExecutor = callbackExecutor;
  }

  @Override public @Nullable CallAdapter<?, ?> get(
      Type returnType, Annotation[] annotations, Retrofit retrofit) {
	//Retrofit中创建CallAdapter的时候,调用get方法,执行到此处
	//可以看到new 了一个CallAdapter
    return new CallAdapter<Object, Call<?>>() {
      @Override public Type responseType() {
        return responseType;
      }

//下面这个adapt肯定要被回调,那什么时候调用的了??
//回到Retrofit中create方法,的动态代理中 loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
//  @Override final @Nullable ReturnT invoke(Object[] args) {
// 创建了一个OkhttpCall
// Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
// return adapt(call, args);}   此处的这个adapt为抽象方法
//通过上面的分析,我们知道loadServiceMethod返回的是:CallAdapted实例
//CallAdapted的adapt()方法,又调用了 callAdapter.adapt(call),callAdapter正是我们当前正在分析的这个DefaultCallAdapterFactory中new 出来的callAdapter
所以动态代理中的invokde来到了下面这行代码:

      @Override public Call<Object> adapt(Call<Object> call) { //所以传进来的这个call就是OkhttpCall
        return executor == null
            ? call
            : new ExecutorCallbackCall<>(executor, call);
      }
    };
  }

  static final class ExecutorCallbackCall<T> implements Call<T> {
    final Executor callbackExecutor;
    final Call<T> delegate;

    ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
      this.callbackExecutor = callbackExecutor;
      this.delegate = delegate; //这个delegate为OkhttpCall
    }
	// 我们是不是使用Retrofit的时候,调用接口方之后就会 enqueue(new CallBack<T>{...}),
	//是的,所以我们调用的哪个enqueue的入口点,正是此处。
    @Override public void enqueue(final Callback<T> callback) {
      Objects.requireNonNull(callback, "callback == null");
	 // 去到OkhttpCall的enqueue方法,
      delegate.enqueue(new Callback<T>() {
        @Override public void onResponse(Call<T> call, final Response<T> response) {
			//可见CallbackExecutor执行execute(),让这次请求回到了主线程中
          callbackExecutor.execute(() -> {
            if (delegate.isCanceled()) {
              // Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
			 //终于回调到了用户请求处
              callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
            } else {
              callback.onResponse(ExecutorCallbackCall.this, response);
            }
          });
        }

        @Override public void onFailure(Call<T> call, final Throwable t) {
          callbackExecutor.execute(() -> callback.onFailure(ExecutorCallbackCall.this, t));
        }
      });
    }

OkHttpCall的enqueue方法

@Override public void enqueue(final Callback<T> callback) {
Objects.requireNonNull(callback, "callback == null");

okhttp3.Call call;
Throwable failure;

synchronized (this) {
  if (executed) throw new IllegalStateException("Already executed.");
  executed = true;

  call = rawCall;
  failure = creationFailure;
  if (call == null && failure == null) {
    try {
	//这个叫做rawCall,可见不是一般的Call,没错,正是OKhttp的Call,而不是retrofit的Call
	// okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
	//上面也就是 okhttp3.Call call = OkhttpClient.newCall( okhttp3.Request)
      call = rawCall = createRawCall();
    } catch (Throwable t) {
      throwIfFatal(t);
      failure = creationFailure = t;
    }
  }
}

if (failure != null) {
  callback.onFailure(this, failure);
  return;
}

if (canceled) {
  call.cancel();
}
//因此这个Call也就是OKhttpClient的call了,终于可以请求网络
call.enqueue(new okhttp3.Callback() {
  @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) {
    Response<T> response;
    try {
		//下面这行代码,拿到了响应体,我们就可以该反序列化的反序列化了
      response = parseResponse(rawResponse);
    } catch (Throwable e) {
      throwIfFatal(e);
      callFailure(e);
      return;
    }

    try {
	//回调回去,准备让executor来一次handler消息切换
      callback.onResponse(OkHttpCall.this, response);
    } catch (Throwable t) {
      throwIfFatal(t);
      t.printStackTrace(); // TODO this is not great
    }
  }

  @Override public void onFailure(okhttp3.Call call, IOException e) {
    callFailure(e);
  }

  private void callFailure(Throwable e) {
    try {
      callback.onFailure(OkHttpCall.this, e);
    } catch (Throwable t) {
      throwIfFatal(t);
      t.printStackTrace(); // TODO this is not great
    }
  }
});}

至此,一次请求的大概过程就是这样。

发布了17 篇原创文章 · 获赞 5 · 访问量 2万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览