0. 前言
Retrofit中關(guān)于 [ 數(shù)據(jù)結(jié)構(gòu) <----> Model ] 之間的相互轉(zhuǎn)換包括兩個方面:
即我們進行源碼分析的兩個突破口
- 請求, 即 通過
@Body
注解添加的自定義 Model --> RequestBody - 響應, 即 ResponseBody --> 自定義Model
這里的數(shù)據(jù)結(jié)構(gòu)包含常用的json, xml , 最關(guān)鍵的是以上兩個操作都是自動完成的, diao的不行, 根本不需要我們手動參與 自己進行解析轉(zhuǎn)換;
那到底是如何做到的呢? 本文以json為例進行詳細分析~
以上兩個方面對應的http request和response 中的header 中的
content-type
都為application/json
1. 用法
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.HOST)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
2. Convert 的簡要說明
關(guān)于json轉(zhuǎn)換部分 具體是通過addConverterFactory()
傳入我們需要的ConverFactory;
也就是說, 最終通過ConverterFactory創(chuàng)建convert 完成從responseBody-> Model的轉(zhuǎn)換; 以下是Converter 接口以及Converter.Factory的源碼
public interface Converter<F, T> {
T convert(F value) throws IOException;
abstract class Factory {
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(Type type,
Annotation[] annotations, Retrofit retrofit) {
return null;
}
public @Nullable Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return null;
}
public @Nullable Converter<?, String> stringConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return null;
}
protected static Type getParameterUpperBound(int index, ParameterizedType type) {
return Utils.getParameterUpperBound(index, type);
}
protected static Class<?> getRawType(Type type) {
return Utils.getRawType(type);
}
}
}
其實看了以上convert接口的源碼就明確了本文的最終目的, 就是convert.convert()
方法具體是在哪調(diào)用的???
關(guān)于Convert的具體實現(xiàn), 如下有很多, 支持市面上大部分開源庫:
我們這里用GsonConverterFactory.
3.源碼分析
(非核心代碼用...
忽略)
3.1 Retrofit 核心代碼
Retrofit.java中最終用來創(chuàng)建service的create方法
public <T> T create(final Class<T> service) {
...
//通過動態(tài)代理創(chuàng)建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 {
...
//1. 創(chuàng)建并緩存ServiceMethod ,這個對象用來解析并包裝我們在service中自定義的各種方法
ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);
//2. call 的包裝類
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//3. 用我們傳入的callAdapter 進行方法返回值的轉(zhuǎn)換
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
這里使用了動態(tài)代理 創(chuàng)建了service接口的代理對象, 因此每次調(diào)用service對象中的方法, 本質(zhì)就是執(zhí)行 invocationHandler.invoke()
方法 (關(guān)于動態(tài)代理的原理這暫且不詳談);
因此每個方法執(zhí)行的核心代碼就上面123 三句話;
而關(guān)于ResponseBody/RequestBody <---> Model的轉(zhuǎn)換就在OkHttpCall
的execute()
中;
@Override public Response<T> execute() throws IOException {
okhttp3.Call call;
...
synchronized (this) {
call = rawCall;
if (call == null) {
//注釋1. request的創(chuàng)建從這里開始
call = rawCall = createRawCall();
}
}
...
//注釋2. response的創(chuàng)建在這里
return parseResponse(call.execute());
}
3.2 Model --> RequestBody的轉(zhuǎn)換
okHttpCall.execute()
方法中注釋1reateRawCall();
創(chuàng)建call
private okhttp3.Call createRawCall() throws IOException {
//核心代碼
Request request = serviceMethod.toRequest(args);
//這里的callFactory取得就是retrofit中的callFactory, 即httpClient
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
...
return call;
}
以上核心代碼便是ServiceMethod中關(guān)于request的創(chuàng)建,
/** Builds an HTTP request from method arguments. */
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;
...
//在這里, 遍歷每個ParameterHandler對 service的方法參數(shù)進行處理
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
return requestBuilder.build();
}
既然我們用的是@Body
注解, 那么直接看Body 這個ParameterHandler的實現(xiàn)
static final class Body<T> extends ParameterHandler<T> {
private final Converter<T, RequestBody> converter;
Body(Converter<T, RequestBody> converter) {
this.converter = converter;
}
@Override void apply(RequestBuilder builder, @Nullable T value) {
...
RequestBody body;
//找到了
body = converter.convert(value);
builder.setBody(body);
}
}
那這個converter又是哪里來的? 其實就是最初我們構(gòu)建retrofit的時候, 通過addConverterFactory()
傳進去的GsonConverterFactory創(chuàng)建的GsonRequestBodyConverter;
以上~
至于ParameterHandler的數(shù)組又是如何初始化的, 各種注解怎么解析的, 都在ServiceMethod這個類里, 慢慢欣賞~
這里只貼一下解析@Body
的源碼
else if (annotation instanceof Body) {
if (isFormEncoded || isMultipart) {
throw parameterError(p,
"@Body parameters cannot be used with form or multi-part encoding.");
}
if (gotBody) {
throw parameterError(p, "Multiple @Body method annotations found.");
}
Converter<?, RequestBody> converter;
try {
//看, 偉大的requestBodyConverter
converter = retrofit.requestBodyConverter(type, annotations, methodAnnotations);
} catch (RuntimeException e) {
// Wide exception range because factories are user code.
throw parameterError(e, p, "Unable to create @Body converter for %s", type);
}
gotBody = true;
return new ParameterHandler.Body<>(converter);
}
3.3 ResponseBody --> Model的轉(zhuǎn)換
okHttpCall.execute()
方法中的最后一句parseResponse(Response rawResp)
創(chuàng)建了Rerofit2.Response<T>
,
看到這個泛型 T 了吧, 其實里面封裝了T body
變量, 也就是我們最終拿到的model
(注意區(qū)別于okhttp中的Response)
Response<T> 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();
...
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;
}
}
下面來看T body = serviceMethod.toResponse(catchingBody);
的實現(xiàn)
/** Builds a method return value from an HTTP response body. */
R toResponse(ResponseBody body) throws IOException {
return responseConverter.convert(body);
}
那上面這個responseConverter又是怎么來的呢? 具體彎彎繞繞就不看了, 其實就是我們在創(chuàng)建retrofit的時候,通過addConverterFactory()
傳進去的GsonConverterFactory創(chuàng)建的GsonResponseBodyConverter;
下面來看直接來看GsonResponseBodyConverter
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override public T convert(ResponseBody value) throws IOException {
JsonReader jsonReader = gson.newJsonReader(value.charStream());
try {
return adapter.read(jsonReader);
} finally {
value.close();
}
}
}
如此, T 也就是我們自定義的Model最終轉(zhuǎn)換完成;
至于okHttpCall.execute()
又是在何時被誰調(diào)用的在這里就不繼續(xù)深究了, 因為不同的callAdapter有不同的實現(xiàn), 已超出本文探究范圍, 要具體探究的話可以看invoke()
中的第3句核心代碼serviceMethod.callAdapter.adapt(okHttpCall);
ps. RxJava的相關(guān)實現(xiàn)在RxJavaCallAdapter