主目录见:Android高级进阶知识(这是总目录索引)
我们知道Retrofit2是基于OkHttp的一个Restful Api请求工具,它是一个类型安全的http客户端请求工具(Type-safe HTTP client for Android and Java ),上一篇文章[OkHttp源码分析]我们已经说了OkHttp的机制,这里我们就来说说Retrofit2了,从功能上来说,Retrofit有点类似Volley,但是使用方式上相对而言Retrofit会更简单,其实Retrofit的源代码还是比较简单的,我们就直接开始吧。
一.目标
我们说Retrofit2的一个初衷是他现在用的比较多,而且能跟比较火的rxjava结合使用,同时Retrofit2内部使用了代理,同时Api的使用通过注解来完成。所以我们今天的目标如下:
1.了解代理的使用场景;
2.通过源码来了解Retrofit的使用。
二.源码分析
首先我们来看看Retrofit基本的用法吧,这也是我们看代码的老套路了:
1.根据Api创建一个java接口,用注解描述方法
public interface PhoneService {
@GET("/")
CallgetResult(@Query("mobile") String phone);
}
2.新建一个Retrofit对象,并指定服务器URL
Retrofit retrofit=new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
3.创建接口对象例如这里的PhoneService,然后得到Call对象
PhoneService service=retrofit.create(PhoneService.class);
Callcall=service.getResult(etPhone.getText().toString());
4.利用Call对象获取数据,有异步和同步之分,这里以异步为例
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
//4.处理结果
if(response.isSuccessful()){
PhoneResult result=response.body();
if (result!=null){
tvLocal.setText(result.getData().getProvince()+".."+result.getData().getCity());
Toast.makeText(MainActivity.this,"网络访问成功!"+result,Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
Toast.makeText(MainActivity.this,"网络访问失败!"+t,Toast.LENGTH_LONG).show();
}
});
我们看到使用的流程还是清晰简单的,在构建Retrofit对象的时候我们看到添加了一个ConverterFactory,同时如果我们跟Rxjava集成还需要添加一个CallAdapterFactory为RxJavaCallAdapterFactory。这个地方就记住就行,免得后面提到不知道哪里出现的。
1.Retrofit create
这个就是获取到一个PhoneService对象了,我们来看看怎么就通过一个PhoneService.class参数就得到这个对象呢?我们直接来看create方法干了什么:
@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public T create(final Class service) {
//验证这个class里面是否有接口
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, @Nullable Object[] args)
throws Throwable {
// If the method is a method from Object then defer to normal invocation.
//如果这个方法是在Object中的,则直接调用
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
//如果这个方法是默认方法(这个默认方法是在java8中引入的),则也直接调用
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
ServiceMethod
我们看到这里使用了java的动态代理,java中的动态代理可以拦截方法的调用来添加额外的功能,这里同样,调用参数class里面方法的时候可以根据里面的注解等信息来拼接我们需要的请求。具体我们来看ServiceMethod的结构:
final class ServiceMethod {
// Upper and lower characters, digits, underscores, and hyphens, starting with a character.
static final String PARAM = "[a-zA-Z][a-zA-Z0-9_-]*";
static final Pattern PARAM_URL_REGEX = Pattern.compile("\\{(" + PARAM + ")\\}");
static final Pattern PARAM_NAME_REGEX = Pattern.compile(PARAM);
final okhttp3.Call.Factory callFactory;
//这个设计主要是针对rxjava设计的,为了将一个Call转化为另外一个对象
final CallAdapter callAdapter;
//服务器基地址
private final HttpUrl baseUrl;
//返回数据转化器
private final Converter responseConverter;
//http请求的方法
private final String httpMethod;
//相对地址
private final String relativeUrl;
//请求头部
private final Headers headers;
//请求的contentType
private final MediaType contentType;
private final boolean hasBody;
private final boolean isFormEncoded;
private final boolean isMultipart;
private final ParameterHandler>[] parameterHandlers;
....
}
我们看到这个类主要是封装了方法的一些信息的,很显然,loadServiceMethod()方法就是为了解析调用的method的信息然后封装到ServiceMethod,我们具体看下这个方法:
ServiceMethod, ?> loadServiceMethod(Method method) {
//serviceMethodCache这是一个key为Method,value为ServiceMethod的Map作为缓存使用
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;
}
我们看到这里首先会看缓存里面是否已经有这个ServiceMethod对象,如果没有则我们会调用ServiceMethod.Builder#build
方法来进行获取,首先我们看ServiceMethod.Builder的构造函数:
Builder(Retrofit retrofit, Method method) {
this.retrofit = retrofit;
this.method = method;
this.methodAnnotations = method.getAnnotations();
this.parameterTypes = method.getGenericParameterTypes();
this.parameterAnnotationsArray = method.getParameterAnnotations();
}
我们看到这个构造函数主要是获取方法,方法的注解,方法的参数类型,方法参数的注解等信息。然后我们来看build()方法:
public ServiceMethod build() {
callAdapter = createCallAdapter();
responseType = callAdapter.responseType();
if (responseType == Response.class || responseType == okhttp3.Response.class) {
throw methodError("'"
+ Utils.getRawType(responseType).getName()
+ "' is not a valid response body type. Did you mean ResponseBody?");
}
responseConverter = createResponseConverter();
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
//省略一些判断
......
int parameterCount = parameterAnnotationsArray.length;
parameterHandlers = new ParameterHandler>[parameterCount];
for (int p = 0; p < parameterCount; p++) {
Type parameterType = parameterTypes[p];
if (Utils.hasUnresolvableType(parameterType)) {
throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
parameterType);
}
Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
if (parameterAnnotations == null) {
throw parameterError(p, "No Retrofit annotation found.");
}
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
//省略一些非空判断
....
return new ServiceMethod<>(this);
}
我们首先来看上面这个方法里面的第一个方法createCallAdapter()做了什么:
private CallAdapter createCallAdapter() {
//返回方法的泛型返回类型,因为Retrofit是类型安全的
Type returnType = method.getGenericReturnType();
if (Utils.hasUnresolvableType(returnType)) {
throw methodError(
"Method return type must not include a type variable or wildcard: %s", returnType);
}
if (returnType == void.class) {
throw methodError("Service methods cannot return void.");
}
//返回方法的所有注解
Annotation[] annotations = method.getAnnotations();
try {
//noinspection unchecked
return (CallAdapter) retrofit.callAdapter(returnType, annotations);
} catch (RuntimeException e) { // Wide exception range because factories are user code.
throw methodError(e, "Unable to create call adapter for %s", returnType);
}
}
我们看到这个方法后面调用retrofit的callAdapter方法,那么我们来看这个方法做了什么:
public CallAdapter, ?> callAdapter(Type returnType, Annotation[] annotations) {
return nextCallAdapter(null, returnType, annotations);
}
我们看到这个方法又调用了nexCallAdapter方法,我们同样直接跟进去:
public CallAdapter, ?> nextCallAdapter(@Nullable CallAdapter.Factory skipPast, Type returnType,
Annotation[] annotations) {
checkNotNull(returnType, "returnType == null");
checkNotNull(annotations, "annotations == null");
int start = adapterFactories.indexOf(skipPast) + 1;
for (int i = start, count = adapterFactories.size(); i < count; i++) {
CallAdapter, ?> adapter = adapterFactories.get(i).get(returnType, annotations, this);
if (adapter != null) {
return adapter;
}
}
//省略一个未找到callAdapter的错误字符串拼接
......
}
我们看到这段代码会遍历adapterFactories,然后取出CallAdapter对象,但是这个adapterFactories有哪些CallAdapter.Factory呢,我们知道我们如果集成rxjava的时候会调用addCallAdapterFactory()方法,这个方法在Retrofit的Builder中,其实就是为了给adapterFactories添加CallAdapter.Factory的,但是如果没有设置的话那又是什么呢?我们来看Retrofit的Builder里面:
public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
adapterFactories.add(checkNotNull(factory, "factory == null"));
return this;
}
public Retrofit build() {
...
// Make a defensive copy of the adapters and add the default Call adapter.
List adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
.....
}
#Platform
@Override CallAdapter.Factory defaultCallAdapterFactory(@Nullable Executor callbackExecutor) {
if (callbackExecutor == null) throw new AssertionError();
return new ExecutorCallAdapterFactory(callbackExecutor);
}
从这里可以看出,我们可以自己通过addCallAdapterFactory添加CallAdapter.Factory对象,如果没有设置系统会使用默认的CallAdapter.Factory为ExecutorCallAdapterFactory。这样我们就知道build()方法里面的createCallAdapter()方法返回的就是ExecutorCallAdapterFactory对象通过get获取得到的CallAdapter了。我们继续看ExecutorCallAdapterFactory的get()方法返回的是什么:
@Override
public CallAdapter, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
if (getRawType(returnType) != Call.class) {
return null;
}
final Type responseType = Utils.getCallResponseType(returnType);
return new CallAdapter>() {
@Override public Type responseType() {
return responseType;
}
@Override public Call adapt(Call call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
};
}
我们看到这个get返回的就是一个CallAdapter对象,同时这个类里面有两个方法responseType返回的是方法的返回值的泛型类型以及一个adapt返回ExecutorCallbackCall对象。这样我们得到CallAdapter对象了,我们回到ServiceMethod#build()
方法里面看到程序里面又调用了createResponseConverter()方法,这个方法是干嘛的呢?这个方法基本与CallAdapter的获取过程是一样的,我们这里就不赘述了。接下来我们看buid方法中的parseMethodAnnotation方法:
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);
if (!Void.class.equals(responseType)) {
throw methodError("HEAD method must use Void as response type.");
}
} 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("@Headers annotation is empty.");
}
headers = parseHeaders(headersToParse);
} else if (annotation instanceof Multipart) {
if (isFormEncoded) {
throw methodError("Only one encoding annotation is allowed.");
}
isMultipart = true;
} else if (annotation instanceof FormUrlEncoded) {
if (isMultipart) {
throw methodError("Only one encoding annotation is allowed.");
}
isFormEncoded = true;
}
}
这个方法主要是根据请求方法上面注解来获取请求地址,请求的参数,请求方法名信息。然后我们继续看build()方法的下一个方法parseParameter,这个方法我们这里说一下他的作用,这个方法主要是解析方法参数的注解等信息,然后封装到ParameterHandler对象里面去,最后每个方法参数对应一个ParameterHandler对象放入parameterHandlers数组里面。到这里我们ServiceMethod的build()方法就完成了,最后返回了ServiceMethod对象。然后我们回归到Retrofit的create方法,我们知道我们程序会把ServiceMethod对象和方法参数args放进OkHttpCall对象里面,我们看下这个构造函数:
OkHttpCall(ServiceMethod serviceMethod, @Nullable Object[] args) {
this.serviceMethod = serviceMethod;
this.args = args;
}
最后Retrofit#create
会调用serviceMethod.callAdapter.adapt(okHttpCall)方法进行进一步封装,我们知道这里的callAdapter就是我们前面说的ExecutorCallAdapterFactory中get()方法返回的CallAdapter,我们看下adapt方法干了什么呢:
@Override public Call adapt(Call call) {
return new ExecutorCallbackCall<>(callbackExecutor, call);
}
我们看到这个方法很简单,其实就是将我们的OkHttpCall对象传给了ExecutorCallbackCall对象了,那么我们最后知道Retrofit#create
方法最终返回的就是ExecutorCallbackCall对象。
2.ExecutorCallbackCall
很明显,根据我们用法知道,我们这里用异步请求距离,我们调用Call对象的enqueue方法,也就是说我们调用的是ExecutorCallbackCall的enqueue,我们看下ExecutorCallbackCall类的这个方法:
@Override public void enqueue(final Callback callback) {
checkNotNull(callback, "callback == null");
delegate.enqueue(new Callback() {
@Override public void onResponse(Call call, final Response response) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
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 call, final Throwable t) {
callbackExecutor.execute(new Runnable() {
@Override public void run() {
callback.onFailure(ExecutorCallbackCall.this, t);
}
});
}
});
}
这里面的delegate就是前面传进去的OkHttpCall对象,所以程序会调用OkHttpCall的enqueue方法:
@Override public void enqueue(final Callback callback) {
checkNotNull(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 {
//获取okhttp3.Call对象
call = rawCall = createRawCall();
} catch (Throwable t) {
failure = creationFailure = t;
}
}
}
if (failure != null) {
callback.onFailure(this, failure);
return;
}
if (canceled) {
call.cancel();
}
//调用okhttp3.Call中的enqueue方法
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
Response response;
try {
response = parseResponse(rawResponse);
} catch (Throwable e) {
callFailure(e);
return;
}
callSuccess(response);
}
@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) {
t.printStackTrace();
}
}
private void callSuccess(Response response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
这个代码看着很长,其实很简单,主要就两处代码,首先我们看第一个注释地方获取okhttp3.Call对象的createRawCall()方法:
private okhttp3.Call createRawCall() throws IOException {
Request request = serviceMethod.toRequest(args);
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
我们看到这个方法主要是先获取到一个request对象,然后利用这个request对象来获取okhttp3.Call对象,首先我们来看这个request对象怎么获取,我们跟进来ServiceMethod里面的toRequest方法:
Request toRequest(@Nullable Object... args) throws IOException {
//实例化一个requestBuilder对象
RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,
contentType, hasBody, isFormEncoded, isMultipart);
@SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
ParameterHandler[] handlers = (ParameterHandler[]) parameterHandlers;
int argumentCount = args != null ? args.length : 0;
if (argumentCount != handlers.length) {
throw new IllegalArgumentException("Argument count (" + argumentCount
+ ") doesn't match expected count (" + handlers.length + ")");
}
//将请求方法里面的参数添加到requestBuilder中
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
return requestBuilder.build();
}
这个方法其实就是根据前面得到的ServiceMethod里面得到的请求方法的请求地址,请求方法,请求的contentType,请求参数等等信息得到一个Request对象。然后我们来看serviceMethod对象中的callFactory到底是什么。我们首先看到callFactory这个变量是在ServiceMethod构造函数的时候构造的:
ServiceMethod(Builder builder) {
this.callFactory = builder.retrofit.callFactory();
}
可以看到,这个callFactory又是retrofit里面的callFactory()方法返回的,我们看下:
public okhttp3.Call.Factory callFactory() {
return callFactory;
}
其实这个方法就是直接返回的Retroft这个类中的callFactory对象,那么这个到底是什么呢?其实在创建Retrofit对象的时候即调用build()方法的时候已经创建了:
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
如果我们没有设置这个okhttp3.Call.Factory,我们就默认是OkHttpClient,也就是说Retrofit2默认使用的是OkHttp来访问网络,所以我们就是调用的OkHttpClient的newCall方法来得到一个okhttp3.Call对象。也就是说最后调用call.enqueue()方法其实就是调用的OkHttp来访问的网络。
3.parseResponse
我们看到调用OkHttp访问网络成功后会调用parseResponse(rawResponse)方法来解析Response:
Response parseResponse(okhttp3.Response rawResponse) throws IOException {
ResponseBody rawBody = rawResponse.body();
// Remove the body's source (the only stateful object) so we can pass the response along.
rawResponse = rawResponse.newBuilder()
.body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
.build();
int code = rawResponse.code();
if (code < 200 || code >= 300) {
try {
// Buffer the entire body to avoid future I/O.
ResponseBody bufferedBody = Utils.buffer(rawBody);
return Response.error(bufferedBody, rawResponse);
} finally {
rawBody.close();
}
}
if (code == 204 || code == 205) {
rawBody.close();
return Response.success(null, rawResponse);
}
ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
try {
T body = serviceMethod.toResponse(catchingBody);
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
// If the underlying source threw an exception, propagate that rather than indicating it was
// a runtime exception.
catchingBody.throwIfCaught();
throw e;
}
}
我们看到前面会进行一些请求返回码的判断来做相应的处理,最后最终会调用ServiceMethod的toResponse()方法来返回body的内容:
R toResponse(ResponseBody body) throws IOException {
return responseConverter.convert(body);
}
我们看到了responseConverter,这个对象我们应该很熟悉了,这个对象就是我们之前用addConverterFactory添加进来的GsonConverterFactory中获取到的GsonResponseBodyConverter呀,所以我们直接看GsonResponseBodyConverter的convert方法:
@Override public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
return adapter.read(jsonReader);
} finally {
value.close();
}
}
如果了解gson的大家都知道TypeAdapter的read()方法将会传入一个JsonReader对象实例并返回反序列化的对象。也就是说会把一个json字符串直接反序列化为一个对象,这样的T类型就会是返回的一个具体的对象。
通过上面的数据解析我们也可以看出,我们还可以自定义一个自己的解析器类似GsonConverterFactory,然后分别重写responseBodyConverter()方法和requestBodyConverter()方法,分别定义两个返回数据的解析器和请求数据的解析器类似GsonResponseBodyConverter和GsonRequestBodyConverter。
总结:Retrofit的整体流程还是比较简单的,通过源码的学习相信大家应该更好地掌握了他的用法以及一些设计思想,还是非常巧妙的,希望大家有享受到这里面的代码分析过程。如果不懂代理,注解,OkHttp等知识的请了解清楚哈。