拆轮子系列:Retrofit2
[TOC]
Retrofit本质上是对OkHttpClient网络交互的封装,它接管的是网络请求前和网络请求后,即HttpRequest封装,HttpResponse处理,网络请求过程则交给OkHttpClient。Retrofit采用了一套非常好的设计思想,使得其提供的各部分功能扩展性强,耦合度低。
Retrofit设计流程如下:
Retrofit详细过程梳理如下:
定义网络接口
ResultType 为原始的 retrofit2.Call:
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
ResultType为RxJava Observable:
public interface StudioApiService {
@GET("/studio/doctors/{docId}/clinics/{clinicId}")
Observable<UserClinic> getClinicItem(
@Path("docId") String docId, @Path("clinicId") String clinicId);
@PUT("/studio/doctors/{docId}/clinics/{clinicId}")
Observable<UserClinic> putClinic(
@Path("docId") String docId, @Path("clinicId") String clinicId,
@Body UserClinic clinic);
@DELETE("/studio/doctors/{docId}/clinics/{clinicId}")
Observable<Void> deleteClinic(
@Path("docId") String docId, @Path("clinicId") String clinicId);
@POST("/studio/doctors/{docId}/clinics")
Observable<UserClinic> postClinic(@Path("docId") String docId, @Body UserClinic clinic);
}
创建Retrofit实例
new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().setLenient().create()))
.addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create(context))
.client(setupClient())
.build();
API 接口的调用
API接口的调用过程:
StudioAPiService apiService = retrofit.create(StudioAPiService.class);
Create过程采用的是动态代理方式,Retrofit为接口类生成一个动态代理,通过这种方式调用接口时Retrofit自动接管了调用的过程。代码如下,其中Proxy.newProxyInstance就是一个标准的动态代理过程
public <T> T create(final Class<T> 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.
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);
}
});
}
调用过程中有关键的三个步骤。
ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
return serviceMethod.callAdapter.adapt(okHttpCall);
这是Retrofit调用的关键三步:
- 创建ServiceMethod:根据传入的method创建,这一步涉及到Annotation的解析等,后面会详解;
- 创建OkHttpCall:根据ServiceMethod创建;
- 执行OkHttpCall进行网络请求,涉及到CallAdapter切换
ServiceMethod
看看 ServiceMethod 的构造函数:
ServiceMethod(Builder<R, T> builder) {
this.callFactory = builder.retrofit.callFactory();
this.callAdapter = builder.callAdapter;
this.baseUrl = builder.retrofit.baseUrl();
this.responseConverter = builder.responseConverter;
this.httpMethod = builder.httpMethod;
this.relativeUrl = builder.relativeUrl;
this.headers = builder.headers;
this.contentType = builder.contentType;
this.hasBody = builder.hasBody;
this.isFormEncoded = builder.isFormEncoded;
this.isMultipart = builder.isMultipart;
this.parameterHandlers = builder.parameterHandlers;
}
成员很多,但这里我们重点关注四个成员:callFactory,callAdapter, responseConverter 和 parameterHandlers。
- callFactory 负责创建 HTTP 请求,HTTP 请求被抽象为了 okhttp3.Call 类,它表示一个已经准备好,可以随时执行的 HTTP 请求;
- callAdapter 把 retrofit2.Call<T> 转为 T(注意和 okhttp3.Call 区分开来,retrofit2.Call<T> 表示的是对一个 Retrofit 方法的调用),这个过程会发送一个 HTTP 请求,拿到服务器返回的数据(通过 okhttp3.Call 实现),并把数据转换为声明的 T 类型对象(通过 Converter<F, T> 实现);
- responseConverter 是 Converter<ResponseBody, T> 类型,负责把服务器返回的数据(JSON、XML、二进制或者其他格式,由 ResponseBody 封装)转化为 T 类型的对象;
- parameterHandlers 则负责解析 API 定义时每个方法的参数,并在构造 HTTP 请求时设置参数;
callFactory
this.callFactory = builder.retrofit.callFactory(),所以 callFactory 实际上由 Retrofit 类提供,而我们在构造 Retrofit 对象时,可以指定 callFactory,如果不指定,将默认设置为一个 okhttp3.OkHttpClient。
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
callFactory具体在什么时候使用呢?
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;
}
serviceMethod.callFactory.newCall(request);这就是她的作用,用来创建一个 okhttp3.Call对象,然后通过这个call对象发起网络请求。
callAdapter
关于Retrofit中的call,涉及到以下三个:
retrofit2.Call接口如下:
public interface Call<T> extends Cloneable {
Response<T> execute() throws IOException;
void enqueue(Callback<T> callback);
boolean isExecuted();
void cancel();
boolean isCanceled();
Call<T> clone();
Request request();
}
retrofit2.OkHttpCall类,这是对retrofit2.Call的实现。Retrofit下的网络请求会被转换成retrofit2.OkHttpCall,其背后则是转换成okhttp3.Call,执行,这里就把具体的网络请求委托给了OkHttpClient执行了。
final class OkHttpCall<T> implements Call<T> {
@Override public void enqueue(final Callback<T> callback) {
checkNotNull(callback, "callback == null");
okhttp3.Call call;
Throwable failure;
...
call.enqueue(new okhttp3.Callback() {
@Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
throws IOException {
Response<T> response;
try {
response = parseResponse(rawResponse);
} catch (Throwable e) {
callFailure(e);
return;
}
callSuccess(response);
}
@Override public void onFailure(okhttp3.Call call, IOException e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callFailure(Throwable e) {
try {
callback.onFailure(OkHttpCall.this, e);
} catch (Throwable t) {
t.printStackTrace();
}
}
private void callSuccess(Response<T> response) {
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
});
}
}
下面再来讲讲serviceMethod.callAdapter.adapt(okHttpCall),以RxJavaCallAdapterFactory中的RxJavaCallAdapter,前者是后者的工厂类。
下来看一下RxJavaCallAdapterFactory的构造方法,注意到isAsync,默认是false,即网络请求默认是同步的。
private RxJavaCallAdapterFactory(@Nullable Scheduler scheduler, boolean isAsync) {
this.scheduler = scheduler;
this.isAsync = isAsync;
}
再来看一下RxJavaCallAdapter究竟如何实现Call对象的adapter(), 很简单,为call对象创建一个RxJava的Observable。其中CallEnqueueOnSubscribe、CallExecuteOnSubscribe最终调用的又是OkHttpCall中的相应的enqueue()、execute()方法
@Override public Object adapt(Call<R> call) {
OnSubscribe<Response<R>> callFunc = isAsync
? new CallEnqueueOnSubscribe<>(call)
: new CallExecuteOnSubscribe<>(call);
OnSubscribe<?> func;
if (isResult) {
func = new ResultOnSubscribe<>(callFunc);
} else if (isBody) {
func = new BodyOnSubscribe<>(callFunc);
} else {
func = callFunc;
}
Observable<?> observable = Observable.create(func);
if (scheduler != null) {
observable = observable.subscribeOn(scheduler);
}
if (isSingle) {
return observable.toSingle();
}
if (isCompletable) {
return observable.toCompletable();
}
return observable;
}
responseConverter
这个很好理解,对Response的解析,将Response转换成最终对象,跟踪代码可以看到。在OkHttpCall中拿到最终的response之后,会调用
T body = serviceMethod.toResponse(catchingBody);
R toResponse(ResponseBody body) throws IOException {
return responseConverter.convert(body);
}
以GsonConverterFactory提供的GsonResponseBodyConverter为例:
@Override public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
return adapter.read(jsonReader);
} finally {
value.close();
}
}
parameterHandlers
每个参数都会有一个 ParameterHandler,由 ServiceMethod#parseParameter 方法负责创建,其主要内容就是解析每个参数使用的注解类型(诸如 Path,Query,Field 等),对每种类型进行单独的处理。构造 HTTP 请求时,我们传递的参数都是字符串,那 Retrofit 是如何把我们传递的各种参数都转化为 String 的呢?还是由 Retrofit 类提供 converter!
其关系流程为:
API Method--(ParameterHandler)--> retrofit2.RequestBuilder --> okhttp3.Request
先来看看ServiceMethod中的toRequest方法:
Request toRequest(@Nullable Object... args) throws IOException {
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<Object>[] handlers = (ParameterHandler<Object>[]) 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 + ")");
}
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
return requestBuilder.build();
}
再来看看RequestBuilder.build() 方法:
Request build() {
HttpUrl url;
HttpUrl.Builder urlBuilder = this.urlBuilder;
if (urlBuilder != null) {
url = urlBuilder.build();
} else {
// No query parameters triggered builder creation, just combine the relative URL and base URL.
//noinspection ConstantConditions Non-null if urlBuilder is null.
url = baseUrl.resolve(relativeUrl);
if (url == null) {
throw new IllegalArgumentException(
"Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl);
}
}
RequestBody body = this.body;
if (body == null) {
// Try to pull from one of the builders.
if (formBuilder != null) {
body = formBuilder.build();
} else if (multipartBuilder != null) {
body = multipartBuilder.build();
} else if (hasBody) {
// Body is absent, make an empty body.
body = RequestBody.create(null, new byte[0]);
}
}
MediaType contentType = this.contentType;
if (contentType != null) {
if (body != null) {
body = new ContentTypeOverridingRequestBody(body, contentType);
} else {
requestBuilder.addHeader("Content-Type", contentType.toString());
}
}
return requestBuilder
.url(url)
.method(method, body)
.build();
}
Multipart 处理
@Multipart 是Retrofit2对多文件上传处理的封装,本质上是对multipart/form-data的封装,这个封装依赖于OkHttp中提供的MultipartBody。先来看一下@Multipart的使用方式:
public interface UploadService {
/**
* @Multipart 这个标记很重要,Retrofit会判断是否有这个标记来对参数重新封装
*
* 针对接口2,参数为MultipartBody, 它本身就是一个RequestBody,Retrofit据此判断不进行再次封装
*/
@Multipart
@POST("/upload")
Call<Void> uploadImages(@Part() List<MultipartBody.Part> parts);
@Multipart
@POST("/upload")
Call<Void> uploadImages(@Part() MultipartBody.Part part, @Part("description") RequestBody description);
@POST("/upload")
Call<Void> uploadImages(@Body MultipartBody body);
}
其中,可以将MultipartBody.Part、MultipartBody的创建封装成通用的两个方法,它们的创建方式都是由OKHttp提供的,目的都是将之转换成OKHttp中的MultipartBody。如下:
public class FileToHttpBody {
public static MultipartBody filesToMultiBody(List<File> files) {
MultipartBody.Builder builder = new MultipartBody.Builder();
for (File file: files) {
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
builder.addFormDataPart("file", file.getName(), requestBody);
}
builder.setType(MultipartBody.FORM);
MultipartBody multipartBody = builder.build();
return multipartBody;
}
public static List<MultipartBody.Part> filesToMultiParts(List<File> files) {
List<MultipartBody.Part> parts = new ArrayList<>();
for (File file: files) {
RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
parts.add(MultipartBody.Part.createFormData("file", file.getName(), requestBody));
}
return parts;
}
}
下面我们再来看一下Retrofit对@Multipart、@Part这两个标签分别干了什么。
@Multipart
private void parseMethodAnnotation(Annotation annotation) {
...
} else if (annotation instanceof Multipart) {
if (isFormEncoded) {
throw methodError("Only one encoding annotation is allowed.");
}
isMultipart = true;
}
...
}
Retrofit根据@Multipart打上标记isMultipart,后续依此封装成MultipartBody。
@Part
private ParameterHandler<?> parseParameterAnnotation(
int p, Type type, Annotation[] annotations, Annotation annotation) {
if (annotation instanceof Part) {
if (!isMultipart) {
throw parameterError(p, "@Part parameters can only be used with multipart encoding.");
}
Part part = (Part) annotation;
gotPart = true;
String partName = part.value();
Class<?> rawParameterType = Utils.getRawType(type);
if (partName.isEmpty()) {
if (Iterable.class.isAssignableFrom(rawParameterType)) {
...
else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
return ParameterHandler.RawPart.INSTANCE;
} else {
throw parameterError(p,
"@Part annotation must supply a name or use MultipartBody.Part parameter type.");
}
} else {
Headers headers =
Headers.of("Content-Disposition", "form-data; name=\"" + partName + "\"",
"Content-Transfer-Encoding", part.encoding());
...
Converter<?, RequestBody> converter =
retrofit.requestBodyConverter(type, annotations, methodAnnotations);
return new ParameterHandler.Part<>(headers, converter);
}
}
}
}
这里,提到了两个ParameterHandler:ParameterHandler.RawPart, ParameterHandler.Part。这两个ParameterHandler直接调用了MultipartBody
中的addPart()方法,其源码如下:
static final class RawPart extends ParameterHandler<MultipartBody.Part> {
static final RawPart INSTANCE = new RawPart();
private RawPart() {
}
@Override void apply(RequestBuilder builder, @Nullable MultipartBody.Part value)
throws IOException {
if (value != null) { // Skip null values.
builder.addPart(value);
}
}
}
static final class Part<T> extends ParameterHandler<T> {
private final Headers headers;
private final Converter<T, RequestBody> converter;
Part(Headers headers, Converter<T, RequestBody> converter) {
this.headers = headers;
this.converter = converter;
}
@Override void apply(RequestBuilder builder, @Nullable T value) {
if (value == null) return; // Skip null values.
RequestBody body;
try {
body = converter.convert(value);
} catch (IOException e) {
throw new RuntimeException("Unable to convert " + value + " to RequestBody", e);
}
builder.addPart(headers, body);
}
}
总结
retrofit2一个将工厂模式发挥到极致的优秀库,值得细细体味。它的整个过程可以总结为以下几个步骤:
- 对网络请求方式的封装,直接以接口呈现;
- 对接口的解析,转换成RequestBuilder,最终转成为okhttp3.Request;
- 将Request构造成retrofit2.OkHttpCall,转换成okhttp3.Call执行;
- 通过CallAdapter接管Call执行回调,回调中涉及到Response的解析转换等