retrofit利用了動態(tài)代理模式,我們只需要寫接口和注解就可以創(chuàng)建request。在結(jié)合rxjava和gson,使得我們在請求網(wǎng)絡(luò)的時候變得非常簡單簡潔。
一、簡單用法
//1.創(chuàng)建api
public interface Api {
@GET("app/checkVersion")
Observable<AppVersionEntity> checkVersion();
}
//2.創(chuàng)建httpClient
OkHttpClient httpClient = new OkHttpClient.Builder().build();
//3.創(chuàng)建api代理服務(wù)
Api api = new Retrofit.Builder()
.baseUrl("baseurl")
.client(httpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(Api.class);
//4.發(fā)起請求
api.checkVersion()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BaseSubscriber<AppVersionEntity>() {
@Override
public void next(AppVersionEntity appVersionEntity) {
Log.e(TAG, "next: ");
}
});
整個請求的發(fā)起非常的簡單,就和平常用rxjava一樣的簡潔。
二、創(chuàng)建請求
1.Retrofit.create()
public <T> T create(final Class<T> service) {
Utils.validateServiceInterface(service);
if (validateEagerly) {
eagerlyValidateMethods(service);
}
//利用動態(tài)代理模式
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);
}
//1.當調(diào)用service的某個方法時這里會進行解析創(chuàng)建相應(yīng)的ServiceMethod
ServiceMethod<Object, Object> serviceMethod =
(ServiceMethod<Object, Object>) loadServiceMethod(method);
//2.創(chuàng)建相應(yīng)的請求
OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
//3.這里添加的是RxJava2CallAdapter,所以返回的是observable
return serviceMethod.callAdapter.adapt(okHttpCall);
}
});
}
最為重要的就是ServiceMethod這個類,這個類負責解析和記錄請求信息。
2.Retrofit.loadServiceMethod()
ServiceMethod<?, ?> loadServiceMethod(Method method) {
//serviceMethodCache保存了已經(jīng)發(fā)起過請求的的serviceMethod對象
ServiceMethod<?, ?> result = serviceMethodCache.get(method);
if (result != null) return result;
synchronized (serviceMethodCache) {
result = serviceMethodCache.get(method);
if (result == null) {
//如果沒有相應(yīng)的緩存記錄,則創(chuàng)建一個新的ServiceMethod對象
result = new ServiceMethod.Builder<>(this, method).build();
serviceMethodCache.put(method, result);
}
}
return result;
}
通過serviceMethodCache存儲之前已發(fā)起過請求的相應(yīng)serviceMethod對象,這樣就不用再進行解析接口方法創(chuàng)建了。
3.ServiceMethod.Builder<>(this, method).build()
public ServiceMethod build() {
//創(chuàng)建callAdapter
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?");
}
//創(chuàng)建轉(zhuǎn)換類
responseConverter = createResponseConverter();
//解析方法注解
for (Annotation annotation : methodAnnotations) {
parseMethodAnnotation(annotation);
}
//判斷參數(shù)合法性
if (httpMethod == null) {
throw methodError("HTTP method annotation is required (e.g., @GET, @POST, etc.).");
}
if (!hasBody) {
if (isMultipart) {
throw methodError(
"Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
}
if (isFormEncoded) {
throw methodError("FormUrlEncoded can only be specified on HTTP methods with "
+ "request body (e.g., @POST).");
}
}
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.");
}
//解析方法注解參數(shù)
parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
}
//判斷參數(shù)合法性
if (relativeUrl == null && !gotUrl) {
throw methodError("Missing either @%s URL or @Url parameter.", httpMethod);
}
if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
throw methodError("Non-body HTTP method cannot contain @Body.");
}
if (isFormEncoded && !gotField) {
throw methodError("Form-encoded method must contain at least one @Field.");
}
if (isMultipart && !gotPart) {
throw methodError("Multipart method must contain at least one @Part.");
}
return new ServiceMethod<>(this);
}
至此我們就已經(jīng)解析創(chuàng)建好了一個包含請求信息的serviceMethod對象,主要是利用反射和解析注解來獲取相應(yīng)的請求信息。
4.創(chuàng)建OkHttpCall請求
4.1.創(chuàng)建Call
okhttp3Call.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;
}
通過serviceMthrod對象來創(chuàng)建相應(yīng)的request。
4.2.創(chuàng)建Observable
RxJava2CallAdapter.adapt()
@Override public Object adapt(Call<R> call) {
//根據(jù)請求是同步還是異步來創(chuàng)建observable
Observable<Response<R>> responseObservable = isAsync
? new CallEnqueueObservable<>(call)
: new CallExecuteObservable<>(call);
Observable<?> observable;
if (isResult) {
observable = new ResultObservable<>(responseObservable);
} else if (isBody) {
observable = new BodyObservable<>(responseObservable);
} else {
observable = responseObservable;
}
//省略部分代碼...
return observable;
}
三、發(fā)起請求
到這里就已經(jīng)創(chuàng)建好了發(fā)起請求的需要的相關(guān)信息了,那么接下來看下是如何發(fā)起請求的。
其實發(fā)起請求的觸發(fā)和rxjava的訂閱是一樣的,當有訂閱4.2創(chuàng)建好的observable時,整個請求就開始了。這里已異步請求來分析(即4.2創(chuàng)建的是CallEnqueueObservable)。
CallEnqueueObservable.subscribeActual()
@Override protected void subscribeActual(Observer<? super Response<T>> observer) {
// Since Call is a one-shot type, clone it for each new observer.
Call<T> call = originalCall.clone();
CallCallback<T> callback = new CallCallback<>(call, observer);
observer.onSubscribe(callback);
call.enqueue(callback);
}
Okhttp3Call.enqueue()執(zhí)行成功之后對response進行轉(zhuǎn)換之后在回調(diào)CallEnqueueObservable中的onResponse()方法
@Override public void onResponse(Call<T> call, Response<T> response) {
if (call.isCanceled()) return;
try {
observer.onNext(response);
if (!call.isCanceled()) {
terminated = true;
observer.onComplete();
}
} catch (Throwable t) {
if (terminated) {
RxJavaPlugins.onError(t);
} else if (!call.isCanceled()) {
try {
observer.onError(t);
} catch (Throwable inner) {
Exceptions.throwIfFatal(inner);
RxJavaPlugins.onError(new CompositeException(t, inner));
}
}
}
}
到這整個請求就已經(jīng)完成了。
總結(jié):
Retrofit通過動態(tài)代理來調(diào)用方法,利用反射和注解來獲取相應(yīng)的請求信息;通過okhtpp進行網(wǎng)絡(luò)請求;在通過rxjava實現(xiàn)響應(yīng)對結(jié)果的轉(zhuǎn)換及回調(diào)。