retrofit-analysis



retrofit-analysis

1 2


retrofit-analysis


On Github MrFuFuFu / retrofit-analysis

Retrofit Analysis

MrFu / @MrFuFuFu

introduction

What is the Retrofit?

A type-safe HTTP client for Android and Java

How to use it?

When to do build request?

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

Executor

CallAdapter!

Call

Show code

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

Question: how to encrypt?

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

Question: Frequently resolution annotation, performance loss?

cache!

ServiceMethod serviceMethod = loadServiceMethod(method);
OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
Call call = callFactory.newCall();
return serviceMethod.callAdapter.adapt(okHttpCall);

go on, ServiceMethod

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();

Question

Hey, do not be shy.

THE END

MrFu
Blog / GitHub
Retrofit Analysis MrFu / @MrFuFuFu