• 1 overview
  • 2 Introduction
  • 3 Process Analysis
  • 4 source architecture https://square.github.io/retrofit/ https://github.com/square/retrofit

1 overview

Retrofit is an HTTP request library for Android and Java

The bottom layer is OkHttp for network requests, and Gson for response parsing


2 Introduction


public interface GitHubService {
    @GET("users/{user}/repos")
    Call<List<Repo>> listRepos(@Path("user") String user);
}
 Copy the code

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
//                .client(getOkHttpClient())
                .addConverterFactory(GsonConverterFactory.create())
 .build();  GitHubService gitHubService = retrofit.create(GitHubService.class);  Call<List<Repo>> repos = gitHubService.listRepos("square");  repos.enqueue(new Callback<List<Repo>>() {  @Override  public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {   }   @Override  public void onFailure(Call<List<Repo>> call, Throwable t) {   }  });  Copy the code

More of OkHttp’s capabilities are needed, such as how interceptors can be constructed to pass OkHttpClient to Retrofit

Here’s an example:

    private static OkHttpClient getOkHttpClient() {
        OkHttpClient httpClient = new OkHttpClient.Builder()
                .addInterceptor(new Interceptor() {
                    @Override
                    public okhttp3.Response intercept(Chain chain) throws IOException {
 Request request = chain.request()  .newBuilder()  .removeHeader("User-Agent")// Remove the old one .addHeader("User-Agent"WebSettings. GetDefaultUserAgent (app)) / / add real head .build();  return chain.proceed(request);  }  }).build();  return httpClient;  } Copy the code

3 Process Analysis

Application layer Transport layer

Core Concepts are all there

You can get a glimpse of a mobile terminal network architecture

The application layer

The transport layer

More contact, less contact in other layer development

4 Source code Structure

Retrofit

  • serviceMethodCache
  • callFactory(OkHttpClient)
  • baseUrl
  • converterFactories
  • callAdapterFactories
  • callbackExecutor

HttpServiceMethod

  • RequestFactory
  • callFactory
  • responseConverter

DefaultCallAdapterFactory

  • get() —> ExecutorCallbackCall
    • callbackExecutor
    • delegate (Call)

GsonConverterFactory

  • gson

OkHttpCall

  • requestFactory
  • args
  • callFactory
  • responseConverter
  • canceled
  • rawCall
  • executed

5 concludes

Retrofit encapsulates Http requests as Java interfaces, with annotations describing the request

Many design highlights:

1 Update UI methods

    static final class MainThreadExecutor implements Executor {
      private final Handler handler = new Handler(Looper.getMainLooper());

      @Override
      public void execute(Runnable r) {
 handler.post(r);  }  } Copy the code

2 Dynamic Proxy

Interface –> Intercepts method calls

Proxy.newProxyInstance(
            service.getClassLoader(),
new Class<? >[] {service},            new InvocationHandler() {
              private final Platform platform = Platform.get();
 private final Object[] emptyArgs = new Object[0];   @Override  public @Nullable 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);  } args = args ! = null ? args : emptyArgs; return platform.isDefaultMethod(method)  ? platform.invokeDefaultMethod(method, service, proxy, args)  : loadServiceMethod(method).invoke(args);  }  }); Copy the code

3 Design Mode

  • Builder pattern: concatenated expressions, constructor arguments are overthought

  • The factory pattern

  • Adapter pattern: Takes multiple features to construct a common object

  • Facade pattern: Encapsulates concrete implementations

  • Observer model

This article is formatted using MDNICE