Retrofit原始碼分析

Humble先生發表於2020-11-08
  • 本文概述

    Retrofit作為主流的網路框架,採用註解和介面的方式封裝請求,使得呼叫過程變得優雅又簡潔,優雅的背後肯定是卓越的設計,所以從原始碼角度分析一下Retrofit是如何做到的,整理成文。

  • 使用回顧

    public interface GitHubService {
    
        @GET("group/{id}/users?sort=desc")
        Call<List<User>> groupList(@Path("id") int groupId);
    
        /**
         * 和上面的是一樣的意義
         *
         * @param groupId
         * @param sort
         * @return
         */
        @GET("group/{id}/users")
        Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
    
        /**
         * 相當於group/{id}/users?options.key[0]=options.value[0] & options.key[1]=options.value[1] & ...
         *
         * @param groupId
         * @param options
         * @return
         */
        @GET("group/{id}/users")
        Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
    
        @POST("users/new")
        Call<User> createUser(@Body User user);
    
        @FormUrlEncoded
        @POST("user/edit")
        Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
    
        @Multipart
        @PUT("user/photo")
        Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
    
        /**
         * 靜態Header
         * @return
         */
        @Headers("Cache-Control: max-age=640000")
        @GET("widget/list")
        Call<List<User>> widgetList();
    
        @Headers({
                "Accept: application/vnd.github.v3.full+json",
                "User-Agent: Retrofit-Sample-App"
        })
        @GET("users/{username}")
        Call<User> getUserS(@Path("username") String username);
    
        /**
         * 動態設定Header
         * @param authorization
         * @return
         */
        @GET("user")
        Call<User> getUser(@Header("Authorization") String authorization);
    
        @GET("user")
        Call<User> getUser(@HeaderMap Map<String, String> headers);
    
    }
    
    public static void retrofitDemo(String url) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    
        GitHubService service = retrofit.create(GitHubService.class);
        try {
            List<User> users = service.groupList(1001).execute().body();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

    可以看到,Retrofit是一種更上層的封裝,你可以設定不同的網路框架client,這裡是OkHttpClient,設定baseUrl,之後會和interface類中的請求註解路由引數結合在一起構成整體的url,不用像OkHttpClient每次請求都要傳入整個url,ConverterFactory可以根據想要解析的格式自由選擇,通常我們使用的都是bean->json、json->bean,現在這部分工作我們可以交給Retrofit去做,其他的Converter還有:

    • Gson: com.squareup.retrofit2:converter-gson
    • Jackson: com.squareup.retrofit2:converter-jackson
    • Moshi: com.squareup.retrofit2:converter-moshi
    • Protobuf: com.squareup.retrofit2:converter-protobuf
    • Wire: com.squareup.retrofit2:converter-wire
    • Simple XML: com.squareup.retrofit2:converter-simplexml
    • JAXB: com.squareup.retrofit2:converter-jaxb
    • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

    通過Retrofit例項構造出呼叫service的例項,呼叫其方法獲取Response資料,簡單的呼叫背後是複雜又巧妙的抽象設計,下面跟著原始碼好好的學習一下它的原理。

  • 原始碼分析

    首先baseUrl就是個驗證並將url解析成http或者https格式並儲存成HttpUrl物件的方法,client方法將OkHttpClient繫結到Retrofit.Builder,addConverterFactory把第三方的解析庫物件新增進一個List<Converter.Factory>型別的集合,build方法就是構建出Retrofit例項:

    public Retrofit build() {
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }
    
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
    
      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }
    
      // Make a defensive copy of the adapters and add the default Call adapter.
      List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
      callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
    
      // Make a defensive copy of the converters.
      List<Converter.Factory> converterFactories =
          new ArrayList<>(
              1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());
    
      // Add the built-in converter factory first. This prevents overriding its behavior but also
      // ensures correct behavior when using converters that consume all types.
      converterFactories.add(new BuiltInConverters());
      converterFactories.addAll(this.converterFactories);
      converterFactories.addAll(platform.defaultConverterFactories());
    
      return new Retrofit(
          callFactory,
          baseUrl,
          unmodifiableList(converterFactories),
          unmodifiableList(callAdapterFactories),
          callbackExecutor,
          validateEagerly);
    }
    

    可以看到,build裡面還加入了容錯預設處理。baseUrl不能為空,這是必須引數之一,callFactory預設OkHttpClient,這裡還有個Executor需要設定,因為我們外面沒有設定過這個,所以它是null,然後通過platform的defaultCallbackExecutor方法建立,platform是通過例項話Builder時通過Platform.get()得到的:

    private static final Platform PLATFORM = findPlatform();
    
    static Platform get() {
      return PLATFORM;
    }
    
    private static Platform findPlatform() {
      return "Dalvik".equals(System.getProperty("java.vm.name"))
          ? new Android() //
          : new Platform(true);
    }
    

    因為我們是android,所以這裡是Dalvik虛擬機器,因此是Android()作為platform,它的defaultCallbackExecutor如下:

    @Override
    public Executor defaultCallbackExecutor() {
      return new MainThreadExecutor();
    }
    
    static final class MainThreadExecutor implements Executor {
      private final Handler handler = new Handler(Looper.getMainLooper());
    
      @Override
      public void execute(Runnable r) {
        handler.post(r);
      }
    }
    

    所以這裡使用MainThreadExecutor作為callbackExecutor,可以看到,Android回撥操作通常都是和UI的互動,所以回撥操作預設是要回到主執行緒操作的。

    再往下需要注意的是converterFactories除了新增我們外面傳入的this.converterFactories之外還新增了一個BuiltInConverters和platform.defaultConverterFactories(),注意新增順序,platform.defaultConverterFactories(),這個方法實現在Platform中:

    List<? extends Converter.Factory> defaultConverterFactories() {
      return hasJava8Types ? singletonList(OptionalConverterFactory.INSTANCE) : emptyList();
    }
    

    hasJava8Types是在Platfrom構造方法中指定的,這裡用的是Android(),所以hasJava8Types預設是false,所以這裡defaultConverterFactories返回emptyList(),所以此時converterFactories裡面有BuiltInConverters和我們設定的一個Converter(這裡是GsonConverterFactory)。

    接下來就是呼叫create獲取介面service物件,那interface是怎樣可能建立物件呢?還有interface方法的註解是如何對映成最後傳送的request的呢?繼續往下看:

    @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
    public <T> T create(final Class<T> service) {
      //檢查service是否符合要求
      validateServiceInterface(service);
      return (T)
          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);
                }
              });
    }
    
    private void validateServiceInterface(Class<?> service) {
      //service必須是interface
      if (!service.isInterface()) {
        throw new IllegalArgumentException("API declarations must be interfaces.");
      }
    	
      //使用雙向佇列儲存service及其繼承的其他interface,add是新增到隊尾,然後從頭部依次讀取判斷每個interface是否符合
      Deque<Class<?>> check = new ArrayDeque<>(1);
      check.add(service);
      while (!check.isEmpty()) {
        Class<?> candidate = check.removeFirst();
        //這裡要求介面不能有泛型
        if (candidate.getTypeParameters().length != 0) {
          StringBuilder message =
              new StringBuilder("Type parameters are unsupported on ").append(candidate.getName());
          if (candidate != service) {
            message.append(" which is an interface of ").append(service.getName());
          }
          throw new IllegalArgumentException(message.toString());
        }
        Collections.addAll(check, candidate.getInterfaces());
      }
    
      //建立retrofit物件時傳入的最後一個引數,表示是否提前執行loadServiceMethod方法
      if (validateEagerly) {
        Platform platform = Platform.get();
        for (Method method : service.getDeclaredMethods()) {
          //不能是default方法和靜態方法。
          //根據isDefaultMethod的javadoc註釋,default方法是非靜態且有body的,這種方法在interface中存在必須需要default修飾符修飾且需要JDK1.8及以上。
          //interface中static修飾的方法需要有方法體
          if (!platform.isDefaultMethod(method) && !Modifier.isStatic(method.getModifiers())) {
            loadServiceMethod(method);
          }
        }
      }
    }
    
    ServiceMethod<?> loadServiceMethod(Method method) {
      //之前的validateEagerly如果是true,那在create中呼叫loadServiceMethod的時候就直接從serviceMethodCache裡面取,因為之前已經建立好了
      ServiceMethod<?> result = serviceMethodCache.get(method);
      if (result != null) return result;
    
      synchronized (serviceMethodCache) {
        result = serviceMethodCache.get(method);
        if (result == null) {
          //建立ServiceMethod的地方
          result = ServiceMethod.parseAnnotations(this, method);
          serviceMethodCache.put(method, result);
        }
      }
      return result;
    }
    

    程式碼的作用我已經在註釋中寫明瞭,現在我們知道了實際上retrofit.create建立的是一個GithubService這個介面的動態代理,所以service.groupList實際上呼叫的動態代理的方法,至於動態代理的物件是怎麼建立的,目前只能追溯到native方法,現在先不考慮JVM是怎麼例項化代理物件的,我們只需要知道,當我們呼叫service.groupList的時候會回撥到Proxy.newProxyInstance的最後一個引數new InvocationHandler()的invoke方法裡,所以最終還是會呼叫loadServiceMethod方法,前面看到,loadServiceMethod方法建立的result返回物件在於ServiceMethod.parseAnnotations(this, method):

    static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
      RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
    
      //getGenericReturnType()會返回程式碼中書寫的型別,比如說T method(){},則會返回T,而getReturnType會返回Object
      Type returnType = method.getGenericReturnType();
      //驗證返回型別是否合法
      if (Utils.hasUnresolvableType(returnType)) {
        throw methodError(
            method,
            "Method return type must not include a type variable or wildcard: %s",
            returnType);
      }
      //返回型別不能是void
      if (returnType == void.class) {
        throw methodError(method, "Service methods cannot return void.");
      }
    
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
    }
    
  
  這個方法首先通過RequestFactory.parseAnnotations建立了一個RequestFactory:
  
  ```java
  static RequestFactory parseAnnotations(Retrofit retrofit, Method method) {
    return new Builder(retrofit, method).build();
  }
Builder(Retrofit retrofit, Method method) {
  this.retrofit = retrofit;
  this.method = method;
  this.methodAnnotations = method.getAnnotations();
  this.parameterTypes = method.getGenericParameterTypes();
  this.parameterAnnotationsArray = method.getParameterAnnotations();
}
RequestFactory build() {
  //解析作用於方法上的註解(做用於方法上的註解可以有多個,所以是迴圈解析)
  for (Annotation annotation : methodAnnotations) {
    parseMethodAnnotation(annotation);
  }

  if (httpMethod == null) {
    throw methodError(method, "HTTP method annotation is required (e.g., @GET, @POST, etc.).");
  }

  if (!hasBody) {
    if (isMultipart) {
      throw methodError(
          method,
          "Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
    }
    if (isFormEncoded) {
      throw methodError(
          method,
          "FormUrlEncoded can only be specified on HTTP methods with "
              + "request body (e.g., @POST).");
    }
  }

  //解析作用於方法引數上的註解(注意parameterAnnotationsArray是一個二維陣列,因為有多個引數,每個引數又可能擁有多個註解,但是隻允許有一個註解)
  int parameterCount = parameterAnnotationsArray.length;
  parameterHandlers = new ParameterHandler<?>[parameterCount];
  for (int p = 0, lastParameter = parameterCount - 1; p < parameterCount; p++) {
    parameterHandlers[p] =
        parseParameter(p, parameterTypes[p], parameterAnnotationsArray[p], p == lastParameter);
  }

  if (relativeUrl == null && !gotUrl) {
    throw methodError(method, "Missing either @%s URL or @Url parameter.", httpMethod);
  }
  if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
    throw methodError(method, "Non-body HTTP method cannot contain @Body.");
  }
  if (isFormEncoded && !gotField) {
    throw methodError(method, "Form-encoded method must contain at least one @Field.");
  }
  if (isMultipart && !gotPart) {
    throw methodError(method, "Multipart method must contain at least one @Part.");
  }

  return new RequestFactory(this);
}

首先呼叫了parseMethodAnnotation解析方法上的註解:

private void parseMethodAnnotation(Annotation annotation) {
  if (annotation instanceof DELETE) {
    parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false);
} else if (annotation instanceof GET) {
    parseHttpMethodAndPath("GET", ((GET) annotation).value(), false);
  } else if (annotation instanceof HEAD) {
    parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false);
  } else if (annotation instanceof PATCH) {
    parseHttpMethodAndPath("PATCH", ((PATCH) annotation).value(), true);
  } else if (annotation instanceof POST) {
    parseHttpMethodAndPath("POST", ((POST) annotation).value(), true);
  } else if (annotation instanceof PUT) {
    parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true);
  } else if (annotation instanceof OPTIONS) {
    parseHttpMethodAndPath("OPTIONS", ((OPTIONS) annotation).value(), false);
  } else if (annotation instanceof HTTP) {
    HTTP http = (HTTP) annotation;
    parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
  } else if (annotation instanceof retrofit2.http.Headers) {
    String[] headersToParse = ((retrofit2.http.Headers) annotation).value();
    if (headersToParse.length == 0) {
      throw methodError(method, "@Headers annotation is empty.");
    }
    headers = parseHeaders(headersToParse);
  } else if (annotation instanceof Multipart) {
    if (isFormEncoded) {
      throw methodError(method, "Only one encoding annotation is allowed.");
    }
    isMultipart = true;
  } else if (annotation instanceof FormUrlEncoded) {
    if (isMultipart) {
      throw methodError(method, "Only one encoding annotation is allowed.");
    }
    isFormEncoded = true;
  }
}

閱讀程式碼可知,判斷Annotation的型別,呼叫parseHttpMethodAndPath對應解析,注意只有PATCH、POST、PUT的hasBody引數傳入的是true,不同的是Headers註解呼叫parseHeaders(),Multipart和FormUrlEncoded(表單)是互斥的,它倆分別結合PUT和POST使用,所以沒有path。首先看一下parseHttpMethodAndPath方法:

private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
  //不允許重複賦值
  if (this.httpMethod != null) {
    throw methodError(
        method,
        "Only one HTTP method is allowed. Found: %s and %s.",
        this.httpMethod,
        httpMethod);
  }
  this.httpMethod = httpMethod;
  this.hasBody = hasBody;
  //如果沒有path則返回
  if (value.isEmpty()) {
    return;
  }

  // Get the relative URL path and existing query string, if present.
  int question = value.indexOf('?');
  if (question != -1 && question < value.length() - 1) {
    // Ensure the query string does not have any named parameters.
    //queryParams是?後面的內容
    String queryParams = value.substring(question + 1);
    //PARAM_URL_REGEX是\{XXX}\這種樣式,不允許出現在?後面,需要使用@Query註解在方法引數裡新增
    Matcher queryParamMatcher = PARAM_URL_REGEX.matcher(queryParams);
    if (queryParamMatcher.find()) {
      throw methodError(
          method,
          "URL query string \"%s\" must not have replace block. "
              + "For dynamic query parameters use @Query.",
          queryParams);
    }
  }
  //比如/table?id=1,this.relativeUrl就是/table?id=1
  this.relativeUrl = value;
  this.relativeUrlParamNames = parsePathParameters(value);
}
static Set<String> parsePathParameters(String path) {
  Matcher m = PARAM_URL_REGEX.matcher(path);
  Set<String> patterns = new LinkedHashSet<>();
  while (m.find()) {
    patterns.add(m.group(1));
  }
  return patterns;
}

parsePathParameters會把?前面的\{paramName}\形式的引數名存到一個LinkedHashSet中,為什麼是鏈式的,因為如果方法引數中沒有指定引數名註解,則會按照順序對應賦值。

parseHeaders就是根據“key:value”的形式去解析鍵值對,Content-Type需要通過MediaType解析:

private Headers parseHeaders(String[] headers) {
  Headers.Builder builder = new Headers.Builder();
  for (String header : headers) {
    int colon = header.indexOf(':');
    if (colon == -1 || colon == 0 || colon == header.length() - 1) {
      throw methodError(
          method, "@Headers value must be in the form \"Name: Value\". Found: \"%s\"", header);
    }
    String headerName = header.substring(0, colon);
    String headerValue = header.substring(colon + 1).trim();
    if ("Content-Type".equalsIgnoreCase(headerName)) {
      try {
        contentType = MediaType.get(headerValue);
      } catch (IllegalArgumentException e) {
        throw methodError(method, e, "Malformed content type: %s", headerValue);
      }
    } else {
      builder.add(headerName, headerValue);
    }
  }
  return builder.build();
}

回到RequestFactory的build,parseParameter解析方法引數:

private @Nullable ParameterHandler<?> parseParameter(
    int p, Type parameterType, @Nullable Annotation[] annotations, boolean allowContinuation) {
  ParameterHandler<?> result = null;
  if (annotations != null) {
    for (Annotation annotation : annotations) {
      ParameterHandler<?> annotationAction =
          parseParameterAnnotation(p, parameterType, annotations, annotation);

      if (annotationAction == null) {
        continue;
      }

      if (result != null) {
        throw parameterError(
            method, p, "Multiple Retrofit annotations found, only one allowed.");
      }

      result = annotationAction;
    }
  }

  if (result == null) {
    if (allowContinuation) {
      try {
        if (Utils.getRawType(parameterType) == Continuation.class) {
          isKotlinSuspendFunction = true;
          return null;
        }
      } catch (NoClassDefFoundError ignored) {
      }
    }
    throw parameterError(method, p, "No Retrofit annotation found.");
  }

  return result;
}

parseParameterAnnotation的原始碼:

@Nullable
private ParameterHandler<?> parseParameterAnnotation(
    int p, Type type, Annotation[] annotations, Annotation annotation) {
  if (annotation instanceof Url) {
    validateResolvableType(p, type);
    if (gotUrl) {
      throw parameterError(method, p, "Multiple @Url method annotations found.");
    }
    if (gotPath) {
      throw parameterError(method, p, "@Path parameters may not be used with @Url.");
    }
    if (gotQuery) {
      throw parameterError(method, p, "A @Url parameter must not come after a @Query.");
    }
    if (gotQueryName) {
      throw parameterError(method, p, "A @Url parameter must not come after a @QueryName.");
    }
    if (gotQueryMap) {
      throw parameterError(method, p, "A @Url parameter must not come after a @QueryMap.");
    }
    if (relativeUrl != null) {
      throw parameterError(method, p, "@Url cannot be used with @%s URL", httpMethod);
    }

    gotUrl = true;

    if (type == HttpUrl.class
        || type == String.class
        || type == URI.class
        || (type instanceof Class && "android.net.Uri".equals(((Class<?>) type).getName()))) {
      return new ParameterHandler.RelativeUrl(method, p);
    } else {
      throw parameterError(
          method,
          p,
          "@Url must be okhttp3.HttpUrl, String, java.net.URI, or android.net.Uri type.");
    }

  } else if (annotation instanceof Path) {
    validateResolvableType(p, type);
    if (gotQuery) {
      throw parameterError(method, p, "A @Path parameter must not come after a @Query.");
    }
    if (gotQueryName) {
      throw parameterError(method, p, "A @Path parameter must not come after a @QueryName.");
    }
    if (gotQueryMap) {
      throw parameterError(method, p, "A @Path parameter must not come after a @QueryMap.");
    }
    if (gotUrl) {
      throw parameterError(method, p, "@Path parameters may not be used with @Url.");
    }
    if (relativeUrl == null) {
      throw parameterError(
          method, p, "@Path can only be used with relative url on @%s", httpMethod);
    }
    gotPath = true;

    Path path = (Path) annotation;
    String name = path.value();
    validatePathName(p, name);

    Converter<?, String> converter = retrofit.stringConverter(type, annotations);
    return new ParameterHandler.Path<>(method, p, name, converter, path.encoded());

  } else if (annotation instanceof Query) {
    validateResolvableType(p, type);
    Query query = (Query) annotation;
    String name = query.value();
    boolean encoded = query.encoded();

    Class<?> rawParameterType = Utils.getRawType(type);
    gotQuery = true;
    if (Iterable.class.isAssignableFrom(rawParameterType)) {
      if (!(type instanceof ParameterizedType)) {
        throw parameterError(
            method,
            p,
            rawParameterType.getSimpleName()
                + " must include generic type (e.g., "
                + rawParameterType.getSimpleName()
                + "<String>)");
      }
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
      Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
      return new ParameterHandler.Query<>(name, converter, encoded).iterable();
    } else if (rawParameterType.isArray()) {
      Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
      Converter<?, String> converter =
          retrofit.stringConverter(arrayComponentType, annotations);
      return new ParameterHandler.Query<>(name, converter, encoded).array();
    } else {
      Converter<?, String> converter = retrofit.stringConverter(type, annotations);
      return new ParameterHandler.Query<>(name, converter, encoded);
    }

  } else if (annotation instanceof QueryName) {
    validateResolvableType(p, type);
    QueryName query = (QueryName) annotation;
    boolean encoded = query.encoded();

    Class<?> rawParameterType = Utils.getRawType(type);
    gotQueryName = true;
    if (Iterable.class.isAssignableFrom(rawParameterType)) {
      if (!(type instanceof ParameterizedType)) {
        throw parameterError(
            method,
            p,
            rawParameterType.getSimpleName()
                + " must include generic type (e.g., "
                + rawParameterType.getSimpleName()
                + "<String>)");
      }
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
      Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
      return new ParameterHandler.QueryName<>(converter, encoded).iterable();
    } else if (rawParameterType.isArray()) {
      Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
      Converter<?, String> converter =
          retrofit.stringConverter(arrayComponentType, annotations);
      return new ParameterHandler.QueryName<>(converter, encoded).array();
    } else {
      Converter<?, String> converter = retrofit.stringConverter(type, annotations);
      return new ParameterHandler.QueryName<>(converter, encoded);
    }

  } else if (annotation instanceof QueryMap) {
    validateResolvableType(p, type);
    Class<?> rawParameterType = Utils.getRawType(type);
    gotQueryMap = true;
    if (!Map.class.isAssignableFrom(rawParameterType)) {
      throw parameterError(method, p, "@QueryMap parameter type must be Map.");
    }
    Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
    if (!(mapType instanceof ParameterizedType)) {
      throw parameterError(
          method, p, "Map must include generic types (e.g., Map<String, String>)");
    }
    ParameterizedType parameterizedType = (ParameterizedType) mapType;
    Type keyType = Utils.getParameterUpperBound(0, parameterizedType);
    if (String.class != keyType) {
      throw parameterError(method, p, "@QueryMap keys must be of type String: " + keyType);
    }
    Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
    Converter<?, String> valueConverter = retrofit.stringConverter(valueType, annotations);

    return new ParameterHandler.QueryMap<>(
        method, p, valueConverter, ((QueryMap) annotation).encoded());

  } else if (annotation instanceof Header) {
    validateResolvableType(p, type);
    Header header = (Header) annotation;
    String name = header.value();

    Class<?> rawParameterType = Utils.getRawType(type);
    if (Iterable.class.isAssignableFrom(rawParameterType)) {
      if (!(type instanceof ParameterizedType)) {
        throw parameterError(
            method,
            p,
            rawParameterType.getSimpleName()
                + " must include generic type (e.g., "
                + rawParameterType.getSimpleName()
                + "<String>)");
      }
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
      Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
      return new ParameterHandler.Header<>(name, converter).iterable();
    } else if (rawParameterType.isArray()) {
      Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
      Converter<?, String> converter =
          retrofit.stringConverter(arrayComponentType, annotations);
      return new ParameterHandler.Header<>(name, converter).array();
    } else {
      Converter<?, String> converter = retrofit.stringConverter(type, annotations);
      return new ParameterHandler.Header<>(name, converter);
    }

  } else if (annotation instanceof HeaderMap) {
    if (type == Headers.class) {
      return new ParameterHandler.Headers(method, p);
    }

    validateResolvableType(p, type);
    Class<?> rawParameterType = Utils.getRawType(type);
    if (!Map.class.isAssignableFrom(rawParameterType)) {
      throw parameterError(method, p, "@HeaderMap parameter type must be Map.");
    }
    Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
    if (!(mapType instanceof ParameterizedType)) {
      throw parameterError(
          method, p, "Map must include generic types (e.g., Map<String, String>)");
    }
    ParameterizedType parameterizedType = (ParameterizedType) mapType;
    Type keyType = Utils.getParameterUpperBound(0, parameterizedType);
    if (String.class != keyType) {
      throw parameterError(method, p, "@HeaderMap keys must be of type String: " + keyType);
    }
    Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
    Converter<?, String> valueConverter = retrofit.stringConverter(valueType, annotations);

    return new ParameterHandler.HeaderMap<>(method, p, valueConverter);

  } else if (annotation instanceof Field) {
    validateResolvableType(p, type);
    if (!isFormEncoded) {
      throw parameterError(method, p, "@Field parameters can only be used with form encoding.");
    }
    Field field = (Field) annotation;
    String name = field.value();
    boolean encoded = field.encoded();

    gotField = true;

    Class<?> rawParameterType = Utils.getRawType(type);
    if (Iterable.class.isAssignableFrom(rawParameterType)) {
      if (!(type instanceof ParameterizedType)) {
        throw parameterError(
            method,
            p,
            rawParameterType.getSimpleName()
                + " must include generic type (e.g., "
                + rawParameterType.getSimpleName()
                + "<String>)");
      }
      ParameterizedType parameterizedType = (ParameterizedType) type;
      Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
      Converter<?, String> converter = retrofit.stringConverter(iterableType, annotations);
      return new ParameterHandler.Field<>(name, converter, encoded).iterable();
    } else if (rawParameterType.isArray()) {
      Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
      Converter<?, String> converter =
          retrofit.stringConverter(arrayComponentType, annotations);
      return new ParameterHandler.Field<>(name, converter, encoded).array();
    } else {
      Converter<?, String> converter = retrofit.stringConverter(type, annotations);
      return new ParameterHandler.Field<>(name, converter, encoded);
    }

  } else if (annotation instanceof FieldMap) {
    validateResolvableType(p, type);
    if (!isFormEncoded) {
      throw parameterError(
          method, p, "@FieldMap parameters can only be used with form encoding.");
    }
    Class<?> rawParameterType = Utils.getRawType(type);
    if (!Map.class.isAssignableFrom(rawParameterType)) {
      throw parameterError(method, p, "@FieldMap parameter type must be Map.");
    }
    Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
    if (!(mapType instanceof ParameterizedType)) {
      throw parameterError(
          method, p, "Map must include generic types (e.g., Map<String, String>)");
    }
    ParameterizedType parameterizedType = (ParameterizedType) mapType;
    Type keyType = Utils.getParameterUpperBound(0, parameterizedType);
    if (String.class != keyType) {
      throw parameterError(method, p, "@FieldMap keys must be of type String: " + keyType);
    }
    Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
    Converter<?, String> valueConverter = retrofit.stringConverter(valueType, annotations);

    gotField = true;
    return new ParameterHandler.FieldMap<>(
        method, p, valueConverter, ((FieldMap) annotation).encoded());

  } else if (annotation instanceof Part) {
    validateResolvableType(p, type);
    if (!isMultipart) {
      throw parameterError(
          method, p, "@Part parameters can only be used with multipart encoding.");
    }
    Part part = (Part) annotation;
    gotPart = true;

    String partName = part.value();
    Class<?> rawParameterType = Utils.getRawType(type);
    if (partName.isEmpty()) {
      if (Iterable.class.isAssignableFrom(rawParameterType)) {
        if (!(type instanceof ParameterizedType)) {
          throw parameterError(
              method,
              p,
              rawParameterType.getSimpleName()
                  + " must include generic type (e.g., "
                  + rawParameterType.getSimpleName()
                  + "<String>)");
        }
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
        if (!MultipartBody.Part.class.isAssignableFrom(Utils.getRawType(iterableType))) {
          throw parameterError(
              method,
              p,
              "@Part annotation must supply a name or use MultipartBody.Part parameter type.");
        }
        return ParameterHandler.RawPart.INSTANCE.iterable();
      } else if (rawParameterType.isArray()) {
        Class<?> arrayComponentType = rawParameterType.getComponentType();
        if (!MultipartBody.Part.class.isAssignableFrom(arrayComponentType)) {
          throw parameterError(
              method,
              p,
              "@Part annotation must supply a name or use MultipartBody.Part parameter type.");
        }
        return ParameterHandler.RawPart.INSTANCE.array();
      } else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
        return ParameterHandler.RawPart.INSTANCE;
      } else {
        throw parameterError(
            method,
            p,
            "@Part annotation must supply a name or use MultipartBody.Part parameter type.");
      }
    } else {
      Headers headers =
          Headers.of(
              "Content-Disposition",
              "form-data; name=\"" + partName + "\"",
              "Content-Transfer-Encoding",
              part.encoding());

      if (Iterable.class.isAssignableFrom(rawParameterType)) {
        if (!(type instanceof ParameterizedType)) {
          throw parameterError(
              method,
              p,
              rawParameterType.getSimpleName()
                  + " must include generic type (e.g., "
                  + rawParameterType.getSimpleName()
                  + "<String>)");
        }
        ParameterizedType parameterizedType = (ParameterizedType) type;
        Type iterableType = Utils.getParameterUpperBound(0, parameterizedType);
        if (MultipartBody.Part.class.isAssignableFrom(Utils.getRawType(iterableType))) {
          throw parameterError(
              method,
              p,
              "@Part parameters using the MultipartBody.Part must not "
                  + "include a part name in the annotation.");
        }
        Converter<?, RequestBody> converter =
            retrofit.requestBodyConverter(iterableType, annotations, methodAnnotations);
        return new ParameterHandler.Part<>(method, p, headers, converter).iterable();
      } else if (rawParameterType.isArray()) {
        Class<?> arrayComponentType = boxIfPrimitive(rawParameterType.getComponentType());
        if (MultipartBody.Part.class.isAssignableFrom(arrayComponentType)) {
          throw parameterError(
              method,
              p,
              "@Part parameters using the MultipartBody.Part must not "
                  + "include a part name in the annotation.");
        }
        Converter<?, RequestBody> converter =
            retrofit.requestBodyConverter(arrayComponentType, annotations, methodAnnotations);
        return new ParameterHandler.Part<>(method, p, headers, converter).array();
      } else if (MultipartBody.Part.class.isAssignableFrom(rawParameterType)) {
        throw parameterError(
            method,
            p,
            "@Part parameters using the MultipartBody.Part must not "
                + "include a part name in the annotation.");
      } else {
        Converter<?, RequestBody> converter =
            retrofit.requestBodyConverter(type, annotations, methodAnnotations);
        return new ParameterHandler.Part<>(method, p, headers, converter);
      }
    }

  } else if (annotation instanceof PartMap) {
    validateResolvableType(p, type);
    if (!isMultipart) {
      throw parameterError(
          method, p, "@PartMap parameters can only be used with multipart encoding.");
    }
    gotPart = true;
    Class<?> rawParameterType = Utils.getRawType(type);
    if (!Map.class.isAssignableFrom(rawParameterType)) {
      throw parameterError(method, p, "@PartMap parameter type must be Map.");
    }
    Type mapType = Utils.getSupertype(type, rawParameterType, Map.class);
    if (!(mapType instanceof ParameterizedType)) {
      throw parameterError(
          method, p, "Map must include generic types (e.g., Map<String, String>)");
    }
    ParameterizedType parameterizedType = (ParameterizedType) mapType;

    Type keyType = Utils.getParameterUpperBound(0, parameterizedType);
    if (String.class != keyType) {
      throw parameterError(method, p, "@PartMap keys must be of type String: " + keyType);
    }

    Type valueType = Utils.getParameterUpperBound(1, parameterizedType);
    if (MultipartBody.Part.class.isAssignableFrom(Utils.getRawType(valueType))) {
      throw parameterError(
          method,
          p,
          "@PartMap values cannot be MultipartBody.Part. "
              + "Use @Part List<Part> or a different value type instead.");
    }

    Converter<?, RequestBody> valueConverter =
        retrofit.requestBodyConverter(valueType, annotations, methodAnnotations);

    PartMap partMap = (PartMap) annotation;
    return new ParameterHandler.PartMap<>(method, p, valueConverter, partMap.encoding());

  } else if (annotation instanceof Body) {
    validateResolvableType(p, type);
    if (isFormEncoded || isMultipart) {
      throw parameterError(
          method, p, "@Body parameters cannot be used with form or multi-part encoding.");
    }
    if (gotBody) {
      throw parameterError(method, p, "Multiple @Body method annotations found.");
    }

    Converter<?, RequestBody> converter;
    try {
      converter = retrofit.requestBodyConverter(type, annotations, methodAnnotations);
    } catch (RuntimeException e) {
      // Wide exception range because factories are user code.
      throw parameterError(method, e, p, "Unable to create @Body converter for %s", type);
    }
    gotBody = true;
    return new ParameterHandler.Body<>(method, p, converter);

  } else if (annotation instanceof Tag) {
    validateResolvableType(p, type);

    Class<?> tagType = Utils.getRawType(type);
    for (int i = p - 1; i >= 0; i--) {
      ParameterHandler<?> otherHandler = parameterHandlers[i];
      if (otherHandler instanceof ParameterHandler.Tag
          && ((ParameterHandler.Tag) otherHandler).cls.equals(tagType)) {
        throw parameterError(
            method,
            p,
            "@Tag type "
                + tagType.getName()
                + " is duplicate of parameter #"
                + (i + 1)
                + " and would always overwrite its value.");
      }
    }

    return new ParameterHandler.Tag<>(tagType);
  }

  return null; // Not a Retrofit annotation.
}

注意retrofit.requestBodyConverter是這裡使用GsonConverter把bean轉化成json的地方,怎麼轉換就交給GsonConverter了。至於Retrofit是在哪裡用上的Converter轉換請求引數的我們放在最後,現在還沒走完請求流程不好理解。

類似於解析方法註解一樣,針對Url、Path、Query、QueryName、QueryMap、Header、HeaderMap、Field、FieldMap、Part、PartMap、Body、Tag這些註解進行解析。

回到ServiceMethod的parseAnnotations方法,接下來會驗證返回型別並最終會返回一個ServiceMethod,看一下Utils.hasUnresolvableType(returnType)方法:

static boolean hasUnresolvableType(@Nullable Type type) {
  if (type instanceof Class<?>) {
    return false;
  }
  //ParameterizedType,比如ArrayList<String>
  if (type instanceof ParameterizedType) {
    ParameterizedType parameterizedType = (ParameterizedType) type;
    //getActualTypeArguments()得到一個包含String的Type陣列,遞迴呼叫會判斷為Class型別
    for (Type typeArgument : parameterizedType.getActualTypeArguments()) {
      if (hasUnresolvableType(typeArgument)) {
        return true;
      }
    }
    return false;
  }
  //GenericArrayType,比如T[]或T[][],
  if (type instanceof GenericArrayType) {
    //getGenericComponentType()會得到T和T[](脫一層陣列)
    return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType());
  }
  //TypeVariable,比如T、E這種表示某種型別的
  if (type instanceof TypeVariable) {
    return true;
  }
  //WildcardType,? extends String這種萬用字元表示的,比如ArrayList<? extends String>這種ParameterType型別的呼叫parameterizedType.getActualTypeArguments()得到? extends String這種WildcardType型別
  if (type instanceof WildcardType) {
    return true;
  }
  String className = type == null ? "null" : type.getClass().getName();
  throw new IllegalArgumentException(
      "Expected a Class, ParameterizedType, or "
          + "GenericArrayType, but <"
          + type
          + "> is of type "
          + className);
}

返回型別驗證沒問題了就會通過parseAnnotations建立一個ServiceMethod,看看HttpServiceMethod.parseAnnotations做了什麼:

static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
    Retrofit retrofit, Method method, RequestFactory requestFactory) {
  boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
  boolean continuationWantsResponse = false;
  boolean continuationBodyNullable = false;

  Annotation[] annotations = method.getAnnotations();
  Type adapterType;
  if (isKotlinSuspendFunction) {
    Type[] parameterTypes = method.getGenericParameterTypes();
    Type responseType =
        Utils.getParameterLowerBound(
            0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
    if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
      // Unwrap the actual body type from Response<T>.
      responseType = Utils.getParameterUpperBound(0, (ParameterizedType) responseType);
      continuationWantsResponse = true;
    } else {
      // TODO figure out if type is nullable or not
      // Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)
      // Find the entry for method
      // Determine if return type is nullable or not
    }

    adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);
    annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);
  } else {
    adapterType = method.getGenericReturnType();
  }

  CallAdapter<ResponseT, ReturnT> callAdapter =
      createCallAdapter(retrofit, method, adapterType, annotations);
  Type responseType = callAdapter.responseType();
  if (responseType == okhttp3.Response.class) {
    throw methodError(
        method,
        "'"
            + getRawType(responseType).getName()
            + "' is not a valid response body type. Did you mean ResponseBody?");
  }
  if (responseType == Response.class) {
    throw methodError(method, "Response must include generic type (e.g., Response<String>)");
  }
  // TODO support Unit for Kotlin?
  if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
    throw methodError(method, "HEAD method must use Void as response type.");
  }

  Converter<ResponseBody, ResponseT> responseConverter =
      createResponseConverter(retrofit, method, responseType);

  okhttp3.Call.Factory callFactory = retrofit.callFactory;
  if (!isKotlinSuspendFunction) {
    return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
  } else if (continuationWantsResponse) {
    //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
    return (HttpServiceMethod<ResponseT, ReturnT>)
        new SuspendForResponse<>(
            requestFactory,
            callFactory,
            responseConverter,
            (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
  } else {
    //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
    return (HttpServiceMethod<ResponseT, ReturnT>)
        new SuspendForBody<>(
            requestFactory,
            callFactory,
            responseConverter,
            (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
            continuationBodyNullable);
  }
}

通過createCallAdapter得到callAdapter:

private static <ResponseT, ReturnT> CallAdapter<ResponseT, ReturnT> createCallAdapter(
    Retrofit retrofit, Method method, Type returnType, Annotation[] annotations) {
  try {
    //noinspection unchecked
    return (CallAdapter<ResponseT, ReturnT>) retrofit.callAdapter(returnType, annotations);
  } catch (RuntimeException e) { // Wide exception range because factories are user code.
    throw methodError(method, e, "Unable to create call adapter for %s", returnType);
  }
}
public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
  return nextCallAdapter(null, returnType, annotations);
}
public CallAdapter<?, ?> nextCallAdapter(
    @Nullable CallAdapter.Factory skipPast, Type returnType, Annotation[] annotations) {
  Objects.requireNonNull(returnType, "returnType == null");
  Objects.requireNonNull(annotations, "annotations == null");

  int start = callAdapterFactories.indexOf(skipPast) + 1;
  for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
    CallAdapter<?, ?> adapter = callAdapterFactories.get(i).get(returnType, annotations, this);
    if (adapter != null) {
      return adapter;
    }
  }

  StringBuilder builder =
      new StringBuilder("Could not locate call adapter for ").append(returnType).append(".\n");
  if (skipPast != null) {
    builder.append("  Skipped:");
    for (int i = 0; i < start; i++) {
      builder.append("\n   * ").append(callAdapterFactories.get(i).getClass().getName());
    }
    builder.append('\n');
  }
  builder.append("  Tried:");
  for (int i = start, count = callAdapterFactories.size(); i < count; i++) {
    builder.append("\n   * ").append(callAdapterFactories.get(i).getClass().getName());
  }
  throw new IllegalArgumentException(builder.toString());
}

可以看到是從callAdapterFactories裡面取的,還記得Retrofit.Builder的build的時候嗎:

// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));
List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
    @Nullable Executor callbackExecutor) {
  DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor);
  return hasJava8Types
      ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
      : singletonList(executorFactory);
}

如果我們通過addCallAdapterFactory設定過CallAdapter則至少會有一個DefaultCallAdapterFactory,按照沒設定的情況,callAdapterFactories.get(i).get(returnType, annotations, this)就會是:

@Override
public @Nullable CallAdapter<?, ?> get(
    Type returnType, Annotation[] annotations, Retrofit retrofit) {
  if (getRawType(returnType) != Call.class) {
    return null;
  }
  //必須是ParameterizedType型別
  if (!(returnType instanceof ParameterizedType)) {
    throw new IllegalArgumentException(
        "Call return type must be parameterized as Call<Foo> or Call<? extends Foo>");
  }
  //getParameterUpperBound內部會通過getActualTypeArguments獲取泛型類的型別,這裡即是List
  final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);

  final Executor executor =
      Utils.isAnnotationPresent(annotations, SkipCallbackExecutor.class)
          ? null
          : callbackExecutor;

  return new CallAdapter<Object, Call<?>>() {
    @Override
    public Type responseType() {
      return responseType;
    }

    @Override
    public Call<Object> adapt(Call<Object> call) {
      return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
    }
  };
}

同理,converter也一樣會走到:

public <T> Converter<ResponseBody, T> nextResponseBodyConverter(
    @Nullable Converter.Factory skipPast, Type type, Annotation[] annotations) {
  Objects.requireNonNull(type, "type == null");
  Objects.requireNonNull(annotations, "annotations == null");

  int start = converterFactories.indexOf(skipPast) + 1;
  for (int i = start, count = converterFactories.size(); i < count; i++) {
    Converter<ResponseBody, ?> converter =
        converterFactories.get(i).responseBodyConverter(type, annotations, this);
    if (converter != null) {
      //noinspection unchecked
      return (Converter<ResponseBody, T>) converter;
    }
  }

先看構造Retrofit時第一個被新增的BuiltInConverters的responseBodyConverter:

@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(
    Type type, Annotation[] annotations, Retrofit retrofit) {
  if (type == ResponseBody.class) {
    return Utils.isAnnotationPresent(annotations, Streaming.class)
        ? StreamingResponseBodyConverter.INSTANCE
        : BufferingResponseBodyConverter.INSTANCE;
  }
  if (type == Void.class) {
    return VoidResponseBodyConverter.INSTANCE;
  }
  if (checkForKotlinUnit) {
    try {
      if (type == Unit.class) {
        return UnitResponseBodyConverter.INSTANCE;
      }
    } catch (NoClassDefFoundError ignored) {
      checkForKotlinUnit = false;
    }
  }
  return null;
}

可見這是泛型類沒有明確指定時的容錯處理。

我們這裡addConverterFactory時傳入了GsonConverterFactory.create(),所以去看看GsonConverterFactory的responseBodyConverter:

@Override
public Converter<ResponseBody, ?> responseBodyConverter(
    Type type, Annotation[] annotations, Retrofit retrofit) {
  TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
  return new GsonResponseBodyConverter<>(gson, adapter);
}

回到HttpServiceMethod的parseAnnotations,最終會返回一個CallAdapted(暫時不考慮kotlin協程的情況)。

然後就是呼叫動態代理中呼叫invoke方法,實際上就是HttpServiceMethod中的invoke方法:

@Override
final @Nullable ReturnT invoke(Object[] args) {
  Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
  return adapt(call, args);
}

也就是CallAdapted中的adapt方法:

 @Override
 protected ReturnT adapt(Call<ResponseT> call, Object[] args) {
    return callAdapter.adapt(call);
 }

所以也就是DefaultCallAdapterFactory的get方法返回的CallAdapter的adapt:

@Override
public Call<Object> adapt(Call<Object> call) {
  return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
}

到現在相當於service.groupList(1001)已經執行完了,接下來就是execute(),也就是這個ExecutorCallbackCall的execute方法:

@Override
public Response<T> execute() throws IOException {
  return delegate.execute();
}

delegate就是上面的OkHttpCall,它的execute是:

@Override
public Response<T> execute() throws IOException {
  okhttp3.Call call;

  synchronized (this) {
    if (executed) throw new IllegalStateException("Already executed.");
    executed = true;

    call = getRawCall();
  }

  if (canceled) {
    call.cancel();
  }

  return parseResponse(call.execute());
}

getRawCall方法最終呼叫方法是:

private okhttp3.Call createRawCall() throws IOException {
  okhttp3.Call call = callFactory.newCall(requestFactory.create(args));
  if (call == null) {
    throw new NullPointerException("Call.Factory returned null.");
  }
  return call;
}

這個callFactory經查詢就是我們Retrofit.Builder().client()傳入的OkHttpClient物件,所以這裡的call.execute()就是OkHttpClient的newCall()的execute,再往下就是OkHttpClient的原始碼了。

至此,Retrofit的網路請求API呼叫過程就結束了。

那麼response是怎麼通過Converter解析的呢?還有個parseResponse方法:

Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
  ResponseBody rawBody = rawResponse.body();

  // Remove the body's source (the only stateful object) so we can pass the response along.
  rawResponse =
      rawResponse
          .newBuilder()
          .body(new NoContentResponseBody(rawBody.contentType(), rawBody.contentLength()))
          .build();

  int code = rawResponse.code();
  if (code < 200 || code >= 300) {
    try {
      // Buffer the entire body to avoid future I/O.
      ResponseBody bufferedBody = Utils.buffer(rawBody);
      return Response.error(bufferedBody, rawResponse);
    } finally {
      rawBody.close();
    }
  }

  if (code == 204 || code == 205) {
    rawBody.close();
    return Response.success(null, rawResponse);
  }

  ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
  try {
    T body = responseConverter.convert(catchingBody);
    return Response.success(body, rawResponse);
  } catch (RuntimeException e) {
    // If the underlying source threw an exception, propagate that rather than indicating it was
    // a runtime exception.
    catchingBody.throwIfCaught();
    throw e;
  }
}

responseConverter.convert(catchingBody)就是答案,responseConverter是前面的responseBodyConverter返回的GsonResponseBodyConverter:

@Override
public T convert(ResponseBody value) throws IOException {
  JsonReader jsonReader = gson.newJsonReader(value.charStream());
  try {
    T result = adapter.read(jsonReader);
    if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
      throw new JsonIOException("JSON document was not fully consumed.");
    }
    return result;
  } finally {
    value.close();
  }
}

下面就是Gson框架的部分了。

前面還有一點沒講就是Retrofit怎麼引用這個converter解析request引數(即方法引數)的呢?

返回的ParameterHandler的子類會被儲存到RequestFactory的parameterHandlers中,後面OkHttpCall呼叫createRawCall的時候有一句callFactory.newCall(requestFactory.create(args)),這個requestFactory.create中有一句handlers[p].apply(requestBuilder, args[p]),handlers就是parameterHandlers,所以這個apply就是ParameterHandler的相關子類中的apply方法,拿ParameterHandler.Body來說:

@Override
void apply(RequestBuilder builder, @Nullable T value) {
  if (value == null) {
    throw Utils.parameterError(method, p, "Body parameter value must not be null.");
  }
  RequestBody body;
  try {
    body = converter.convert(value);
  } catch (IOException e) {
    throw Utils.parameterError(method, e, p, "Unable to convert " + value + " to RequestBody");
  }
  builder.setBody(body);
}

converter.convert就呼叫到了前面設定的GsonRequestBodyConverter。

  • 總結

    通過原始碼深刻理解了從呼叫到解析,Retrofit是如何優雅的通過註解和動態代理的方式把OkHttpClient的呼叫封裝起來,從而使得彼此之間地耦合度大大地降低地。

相關文章