Retrofit Analysis
A type-safe HTTP client for Android and Java
Use annotations to describe the HTTP request
Annotations on the interface methods and its parameters indicate how a request will be handled.
HttpUrlConnection request way
Annotation Types
CallAdapter!
Call
mWebService = retrofit.create(HaiHuService.class);
Retrofit build
Retrofit create proxy for API interface
API method intercepted by proxy
parse params with ServiceMethod
build HttpCall with params
CallAdapter adapts Call to T
enqueue() waiting for callback
encrypt!
HttpUrlConnection,对 OutputStream write 进行加密
os = conn.getOutputStream(); byte[] compressData = compress(content); os.write(RC4Util.decry_RC4(compressData, RC4_KEY)); os.flush();
GsonConverterFactory
Retrofit.build() OkHttpClient callbackExecutor callAdapter convertor return retrofit
cache!
ServiceMethod serviceMethod = loadServiceMethod(method); OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args); Call call = callFactory.newCall(); return serviceMethod.callAdapter.adapt(okHttpCall);
Adapter type:
Q: How to know use which one adapter?
Here Call.class is
RxJavaCallAdapterFactory
Here Observable.class is
ServiceMethod.build() createCallAdapter createConvertor pareseAnnotation
Call -> ExecutorCallbackCall (ExecutorCallAdapterFactory)
delegate is OkHttpCall, .enqueue to do network request
All these are through OkHttpCall to do HTTP client
ExecutorCallbackCall<> callAdapter.adapt(OkHttpCall<>) ExecutorCallbackCall.enqueue(new Callback()){ okHttpCall.enqueue(new Callback1){ handler.post(new Runnable(){ callback.onResponse.... }) } }
Q: Where is the converter call?
A: ServiceMethod just like a controller
OkHttpCall
requestConvertor okhttp3.Request = okHttpCall.toRequest() responseConvertor //转化成 retrofit 中需要的 response Retrofit.Response = okhttpCall.toResponse();
Hey, do not be shy.