本平臺的文章更新會有延遲,你們能夠關注微信公衆號-顧林海,包括年末前會更新kotlin由淺入深系列教程,目前計劃在微信公衆號進行首發,若是你們想獲取最新教程,請關注微信公衆號,謝謝!java
在上一節《Android小知識-剖析Retrofit中ServiceMethod相關參數以及建立過程》介紹了動態代理類中三行核心代碼的第一行,經過loadServiceMethod方法獲取ServiceMethod對象,在loadServiceMethod方法中先會檢查緩存集合中是否有對應網絡請求接口方法的ServiceMethod對象,若是不存在就經過Builder模式建立,同時介紹了ServiceMethod內部的一些成員變量,其實ServiceMethod就是對網絡請求接口內部一個個方法的封裝,經過解析方法內部或方法上的註解來封裝ServiceMethod對象。這節來介紹三行核心代碼的剩餘兩行。web
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 {
...
//核心代碼1
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
//核心代碼2
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//核心代碼3
return serviceMethod.adapt(okHttpCall);
}
});
}
複製代碼
在覈心代碼2處建立OkHttpCall,OkHttpCall是Call的實現類,在Retrofit中內部是經過OkHttp來進行網絡的請求,這個OkHttpCall就是對OkHttp請求的封裝。緩存
final class OkHttpCall<T> implements Call<T> {
....
private @Nullable okhttp3.Call rawCall;
OkHttpCall(ServiceMethod<T, ?> serviceMethod, @Nullable Object[] args) {
this.serviceMethod = serviceMethod;
this.args = args;
}
}
複製代碼
在OkHttpCall中能夠看到rawCall,它是OkHttp的Call,這也驗證以前所說的內部會經過OkHttp來實現網絡請求,OkHttpCall構造函數傳入兩個參數,serviceMethod對象和args網絡請求參數,接着看核心代碼3。服務器
return serviceMethod.adapt(okHttpCall);
複製代碼
serviceMethod的adapt方法中會調用callAdatper的adapter方法,經過適配器的adapt方法來將OkHttpCall轉換成其餘平臺使用的對象,這個callAdapter是在建立serviceMethod時經過構建者模式建立的,它表明網絡請求的適配器,這裏使用的RxJava平臺。微信
回到一開始的實例代碼:網絡
private void initRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://icould.glh/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
NetworkInterface networkInterface = retrofit.create(NetworkInterface.class);
Map<String, String> params = new HashMap<>();
params.put("newsId", "1");
params.put("token", "yud133f");
Call call = networkInterface.getNewsDetails(params);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
System.out.println(response.body());
}
@Override
public void onFailure(Call call, Throwable t) {
System.out.println("請求錯誤");
}
});
}
複製代碼
經過networkInterface接口調用getNewsDetails是不行的,所以在Retrofit的create獲取網絡接口的動態代理,在執行networkInterface的getNewDetails方法時,經過動態代理攔截,並執行動態代理對象內InvocationHandler中的invoke方法,將OkHttpCall轉換成RxJava平臺的適用的Call,而這個OkHttpCall對象是對OkHttp網絡庫的封裝,最後返回OkHttpCall類型的Call對象,有了這個Call對象就能夠進行同步或異步請求,OkHttpCall內提供了同步請求方法execute和異步請求方法enqueue,接着下來重點分析這兩個方法。app
在Retrofit同步請求流程中,首先須要對網絡請求接口中方法以及參數進行解析,經過ParameterHandler進行解析,而後根據ServiceMethod對象建立OkHttp的Request對象,ServiceMethod對象內部包含了網絡請求的全部信息,它是對網絡接口方法的封裝,有了Request對象後就能夠經過OkHttp這個庫來進行網絡請求,最後解析服務端給客戶端返回的數據,經過converter數據轉換器來完成數據的轉換。框架
OkHttpCall的同步請求execute方法:異步
@Override public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
if (creationFailure != null) {
if (creationFailure instanceof IOException) {
throw (IOException) creationFailure;
} else if (creationFailure instanceof RuntimeException) {
throw (RuntimeException) creationFailure;
} else {
throw (Error) creationFailure;
}
}
call = rawCall;
if (call == null) {
try {
call = rawCall = createRawCall();
} catch (IOException | RuntimeException | Error e) {
throwIfFatal(e); // Do not assign a fatal error to creationFailure.
creationFailure = e;
throw e;
}
}
}
if (canceled) {
call.cancel();
}
return parseResponse(call.execute());
}
複製代碼
下面貼出execute局部代碼,方便分析。ide
@Override public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
if (creationFailure != null) {
if (creationFailure instanceof IOException) {
throw (IOException) creationFailure;
} else if (creationFailure instanceof RuntimeException) {
throw (RuntimeException) creationFailure;
} else {
throw (Error) creationFailure;
}
}
...
}
...
}
複製代碼
上面代碼中一開始建立了一個OkHttp的call對象,下面是一個同步代碼塊,經過判斷executed是否執行過經過請求,若是執行過就會拋出異常,接着判斷creationFailure,不爲null時,判斷異常類型並拋出異常,execute方法的前段部分就是對異常的判斷。
@Override public Response<T> execute() throws IOException {
okhttp3.Call call;
synchronized (this) {
...
call = rawCall;
if (call == null) {
try {
call = rawCall = createRawCall();
} catch (IOException | RuntimeException | Error e) {
throwIfFatal(e); // Do not assign a fatal error to creationFailure.
creationFailure = e;
throw e;
}
}
}
...
}
複製代碼
當沒有任何異常時,將rawCall也就是OkHttp的原生call賦值給局部變量call,當call爲null時,經過createRawCall方法建立OkHttp的Call對象以及Request。
進入createRawCall方法:
private okhttp3.Call createRawCall() throws IOException {
okhttp3.Call call = serviceMethod.toCall(args);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
複製代碼
內部經過serviceMethod的toCall方法將傳入的請求參數轉換成Call對象。
進入serviceMethod的toCall方法:
okhttp3.Call toCall(@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;
...
for (int p = 0; p < argumentCount; p++) {
handlers[p].apply(requestBuilder, args[p]);
}
return callFactory.newCall(requestBuilder.build());
}
複製代碼
RequestBuilder內部保存着網絡請求的相關參數,接着在for循環中經過ParameterHandler對參數進行解析,最後經過callFactory的newCall建立OkHttp的Call對象,newCall內部傳入的是Request對象,經過requestBuilder.build()建立Request對象,到這裏將OkHttp的Call對象返回給execute方法內部的成員變量call以及OkHttpCall的成員變量rawCall。
@Override public Response<T> execute() throws IOException {
okhttp3.Call call;
...
if (canceled) {
call.cancel();
}
return parseResponse(call.execute());
}
複製代碼
有了OkHttp的Call以後,就經過call.execute()進行阻塞式的同步請求,並將返回的Response傳入parseResponse方法中。
進入parseResponse方法:
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
...
try {
T body = serviceMethod.toResponse(catchingBody);
return Response.success(body, rawResponse);
} catch (RuntimeException e) {
...
}
}
複製代碼
只看核心代碼,經過調用serviceMethod的toResponse方法返回body,進入toResponse方法,看它到底作了哪些操做。
R toResponse(ResponseBody body) throws IOException {
return responseConverter.convert(body);
}
複製代碼
原來是調用了數據轉換器將OkHttp返回的Response轉換成Java對象,這裏咱們使用的Gson,也就是經過Gson將服務器返回的數據轉換成咱們須要的Java對象,最後經過Response的success方法將返回的Java對象封裝成Response。
Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
...
return Response.success(body, rawResponse);
}
複製代碼
進入Response的success方法:
public static <T> Response<T> success(@Nullable T body, okhttp3.Response rawResponse) {
...
return new Response<>(rawResponse, body, null);
}
複製代碼
返回建立好的Response,將body也就是咱們的Java對象傳過去。
Response的構造函數:
private Response(okhttp3.Response rawResponse, @Nullable T body, @Nullable ResponseBody errorBody) {
this.rawResponse = rawResponse;
this.body = body;
this.errorBody = errorBody;
}
複製代碼
到這裏你們應該很熟悉了,咱們利用Retrofit進行網絡的同步或異步請求,最終會返回一個Response對象並經過response.body來獲取結果,這個body就是經過轉換器轉換好的Java對象。
接下來分析異步請求:
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
System.out.println(response.body());
}
@Override
public void onFailure(Call call, Throwable t) {
System.out.println("請求錯誤");
}
});
複製代碼
執行異步請求的流程和同步相似,只不過異步請求的結果是經過回調來傳遞的,異步是經過enqueue方法來執行的,而這個Call的實現類是OkHttpCall,進入OkHttpCall的enqueue方法。
OkHttpCall的enqueue方法(上半部分):
@Override public void enqueue(final Callback<T> callback) {
...
okhttp3.Call call;
...
synchronized (this) {
if (executed) throw new IllegalStateException("Already executed.");
executed = true;
call = rawCall;
failure = creationFailure;
if (call == null && failure == null) {
try {
call = rawCall = createRawCall();
} catch (Throwable t) {
throwIfFatal(t);
failure = creationFailure = t;
}
}
}
...
}
複製代碼
能夠發現enqueue的上半部分與上面介紹同步請求時是同樣的,建立OkHttp的Call,並檢查相關異常,若是call爲null,就經過createRawCall方法建立OkHttp的Call以及請求所須要的Request。
OkHttpCall的enqueue方法(下半部分):
@Override public void enqueue(final Callback<T> callback) {
...
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) {
callFailure(e);
return;
}
try {
callback.onResponse(OkHttpCall.this, response);
} catch (Throwable t) {
t.printStackTrace();
}
}
...
});
}
複製代碼
上面這段代碼不用我講,你們也應該知道就是經過OkHttp的Call的enqueue方法進行異步請求,關於OkHttp相關知識能夠閱讀以前寫的OkHttp分析的相關係列教程,在OkHttp的Call的enqueue方法的回調方法onResponse方法中,將返回的Response經過parseResponse方法轉換成Java對象並返回Retrofit的Response對象,經過前面傳入的Callback對象將Response回調給客戶端。
到這裏關於Retrofit網絡請求框架的封裝就講解完畢了!