专栏首页曾大稳的博客retrofit 源码分析

retrofit 源码分析

retrofit的初始化

private static Retrofit RETROFIT;
private static Retrofit getRetrofit() {
    if (RETROFIT == null) {
        RETROFIT = new Retrofit.Builder()
                .client(getHttpClient())
                .baseUrl(BuildConfig.SERVER_URL)
                .addConverterFactory(NobodyConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
                        .registerTypeAdapter(new TypeToken<HashMap<String, Object>>() {
                        }.getType(), new MapTypeAdapter()).create()))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }
    return RETROFIT;
}


static OkHttpClient getHttpClient() {
    return new OkHttpClient.Builder()
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(15, TimeUnit.SECONDS)
            .writeTimeout(15, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .addInterceptor(AccessTokenInterceptor.getInstance())
            .addInterceptor(new RefreshTokenInterceptor(
                    BuildConfig.SERVER_URL))
            .addInterceptor(new ErrorPreviewInterceptor())
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    LogUtils.i(TAG, message);
                }
            }).setLevel(HttpLoggingInterceptor
                    .Level.BODY))
            .build();
}

Refofit.Builder: 初始化过程

/**
   * Build a new {@link Retrofit}.
   * <p>
   * Calling {@link #baseUrl} is required before calling {@link #build()}. All other methods
   * are optional.
   */
  public static final class Builder {
    //平台  android? java8?  ios?
    private final Platform platform;
    //ok3网络请求Factory
    private okhttp3.Call.Factory callFactory;
    // host
    private HttpUrl baseUrl;
    // 数据转换器 request和responseBody解析器  string -->gson-->T
    private final List<Converter.Factory> converterFactories = new ArrayList<>();
    // ok3返回的 response 转换器  response--> rxjava对象
    private final List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
    //线程调度
    private Executor callbackExecutor;
    //如果设置为true  在service  create的时候就先把方法参数解析出来加入缓存
    //设置为false   在调用这个函数的时候在加入缓存
    private boolean validateEagerly;

    Builder(Platform platform) {
      this.platform = platform;
      // 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());
    }

    public Builder() {
        
      this(Platform.get());
    }

    Builder(Retrofit retrofit) {
      platform = Platform.get();
      callFactory = retrofit.callFactory;
      baseUrl = retrofit.baseUrl;
      converterFactories.addAll(retrofit.converterFactories);
      adapterFactories.addAll(retrofit.adapterFactories);
      // Remove the default, platform-aware call adapter added by build().
      adapterFactories.remove(adapterFactories.size() - 1);
      callbackExecutor = retrofit.callbackExecutor;
      validateEagerly = retrofit.validateEagerly;
    }

 
    /**
     * Create the {@link Retrofit} instance using the configured values.
     * <p>
     * Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link
     * OkHttpClient} will be created and used.
     */
    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> adapterFactories = new ArrayList<>(this.adapterFactories);
      adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));

      // Make a defensive copy of the converters.
      List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);

      return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
          callbackExecutor, validateEagerly);
    }
  }

create

public <T> T create(final Class<T> service) {
   Utils.validateServiceInterface(service);
   if (validateEagerly) {
     eagerlyValidateMethods(service);
   }
   //动态代理
   return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
       new InvocationHandler() {
         //Android 
         private final Platform platform = Platform.get();

         @Override public Object invoke(Object proxy, Method method, Object[] args)
             throws Throwable {
           // If the method is a method from Object then defer to normal invocation.
           //如果是object的函数  直接执行
           if (method.getDeclaringClass() == Object.class) {
             return method.invoke(this, args);
           }
           //如果是platform的默认函数  预留的一个钩子
           if (platform.isDefaultMethod(method)) {
             return platform.invokeDefaultMethod(method, service, proxy, args);
           }
           //加载service的方法
           ServiceMethod<Object, Object> serviceMethod =
               (ServiceMethod<Object, Object>) loadServiceMethod(method);
           //根据ServiceMethod得到ok3的网络请求call
           OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
           //网络请求  数据转换  返回数据
           return serviceMethod.callAdapter.adapt(okHttpCall);
         }
       });
 }

loadServiceMethod: 拿到对应的解析器,根据注解解析方法的返回类型,方法参数,网络请求的一系列参数 封装成一个对象

 ServiceMethod<?, ?> loadServiceMethod(Method method) {
    // 读缓存
    ServiceMethod<?, ?> result = serviceMethodCache.get(method);
    if (result != null) return result;
        
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        //得到ServiceMethod对象
        result = new ServiceMethod.Builder<>(this, method).build();
        //加入缓存
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

ServiceMethod:

 Builder(Retrofit retrofit, Method method) {
      this.retrofit = retrofit;
      this.method = method;
      this.methodAnnotations = method.getAnnotations();
      this.parameterTypes = method.getGenericParameterTypes();
      this.parameterAnnotationsArray = method.getParameterAnnotations();
    }

public ServiceMethod build() {
       //根据返回类型以及retrofit的adapterFactories拿到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?");
      }
      //根据responseType通过retrofit的converterFactories拿到 responseBody解析器
      responseConverter = createResponseConverter();

        //后面都是解析注解  拼接参数 
      for (Annotation annotation : methodAnnotations) {
        parseMethodAnnotation(annotation);
      }

      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.");
        }

        parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
      }

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

OkHttpCall:是一个ok3的call ,用于网络请求

/*
 * Copyright (C) 2015 Square, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package retrofit2;

import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;

final class OkHttpCall<T> implements Call<T> {
  private final ServiceMethod<T, ?> serviceMethod;
  private final Object[] args;

  private volatile boolean canceled;

  // All guarded by this.
  private okhttp3.Call rawCall;
  private Throwable creationFailure; // Either a RuntimeException or IOException.
  private boolean executed;

  OkHttpCall(ServiceMethod<T, ?> serviceMethod, Object[] args) {
    this.serviceMethod = serviceMethod;
    this.args = args;
  }

  @SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
  @Override public OkHttpCall<T> clone() {
    return new OkHttpCall<>(serviceMethod, args);
  }

    //请求
  @Override public synchronized Request request() {
    okhttp3.Call call = rawCall;
    if (call != null) {
      return call.request();
    }
    if (creationFailure != null) {
      if (creationFailure instanceof IOException) {
        throw new RuntimeException("Unable to create request.", creationFailure);
      } else {
        throw (RuntimeException) creationFailure;
      }
    }
    try {
      return (rawCall = createRawCall()).request();
    } catch (RuntimeException e) {
      creationFailure = e;
      throw e;
    } catch (IOException e) {
      creationFailure = e;
      throw new RuntimeException("Unable to create request.", e);
    }
  }
    
    //异步请求
  @Override public void enqueue(final Callback<T> callback) {
    if (callback == null) throw new NullPointerException("callback == null");

    okhttp3.Call call;
    Throwable failure;

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

      call = rawCall;
      failure = creationFailure;
      if (call == null && failure == null) {
        try {
          call = rawCall = createRawCall();
        } catch (Throwable t) {
          failure = creationFailure = t;
        }
      }
    }

    if (failure != null) {
      callback.onFailure(this, failure);
      return;
    }

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

    call.enqueue(new okhttp3.Callback() {
      @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
          throws IOException {
        Response<T> response;
        try {
          response = parseResponse(rawResponse);
        } catch (Throwable e) {
          callFailure(e);
          return;
        }
        callSuccess(response);
      }

      @Override public void onFailure(okhttp3.Call call, IOException e) {
        try {
          callback.onFailure(OkHttpCall.this, e);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      private void callFailure(Throwable e) {
        try {
          callback.onFailure(OkHttpCall.this, e);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }

      private void callSuccess(Response<T> response) {
        try {
          callback.onResponse(OkHttpCall.this, response);
        } catch (Throwable t) {
          t.printStackTrace();
        }
      }
    });
  }

  @Override public synchronized boolean isExecuted() {
    return executed;
  }

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

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

      if (creationFailure != null) {
        if (creationFailure instanceof IOException) {
          throw (IOException) creationFailure;
        } else {
          throw (RuntimeException) creationFailure;
        }
      }

      call = rawCall;
      if (call == null) {
        try {
          call = rawCall = createRawCall();
        } catch (IOException | RuntimeException e) {
          creationFailure = e;
          throw e;
        }
      }
    }

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

    return parseResponse(call.execute());
  }
    
    //创建realCall ok3的
  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;
  }

    //解析response
  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);
    }

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
    //通过response解析器进行类型转换
      T body = serviceMethod.toResponse(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;
    }
  }

  public void cancel() {
    canceled = true;

    okhttp3.Call call;
    synchronized (this) {
      call = rawCall;
    }
    if (call != null) {
      call.cancel();
    }
  }

  @Override public boolean isCanceled() {
    if (canceled) {
      return true;
    }
    synchronized (this) {
      return rawCall != null && rawCall.isCanceled();
    }
  }

  static final class NoContentResponseBody extends ResponseBody {
    private final MediaType contentType;
    private final long contentLength;

    NoContentResponseBody(MediaType contentType, long contentLength) {
      this.contentType = contentType;
      this.contentLength = contentLength;
    }

    @Override public MediaType contentType() {
      return contentType;
    }

    @Override public long contentLength() {
      return contentLength;
    }

    @Override public BufferedSource source() {
      throw new IllegalStateException("Cannot read raw response body of a converted body.");
    }
  }

  static final class ExceptionCatchingRequestBody extends ResponseBody {
    private final ResponseBody delegate;
    IOException thrownException;

    ExceptionCatchingRequestBody(ResponseBody delegate) {
      this.delegate = delegate;
    }

    @Override public MediaType contentType() {
      return delegate.contentType();
    }

    @Override public long contentLength() {
      return delegate.contentLength();
    }

    @Override public BufferedSource source() {
      return Okio.buffer(new ForwardingSource(delegate.source()) {
        @Override public long read(Buffer sink, long byteCount) throws IOException {
          try {
            return super.read(sink, byteCount);
          } catch (IOException e) {
            thrownException = e;
            throw e;
          }
        }
      });
    }

    @Override public void close() {
      delegate.close();
    }

    void throwIfCaught() throws IOException {
      if (thrownException != null) {
        throw thrownException;
      }
    }
  }
}

CallAdapter的选择:ServiceMethon.createCallAdapter()–>retrofit.callAdapter() –>retrofit.nextCallAdapter() –>adapterFactories.get();

/**
 * Returns the {@link CallAdapter} for {@code returnType} from the available {@linkplain
 * #callAdapterFactories() factories} except {@code skipPast}.
 *
 * @throws IllegalArgumentException if no call adapter available for {@code type}.
 */
public CallAdapter<?, ?> nextCallAdapter(CallAdapter.Factory skipPast, Type returnType,
    Annotation[] annotations) {
  checkNotNull(returnType, "returnType == null");
  checkNotNull(annotations, "annotations == null");

  int start = adapterFactories.indexOf(skipPast) + 1;
  for (int i = start, count = adapterFactories.size(); i < count; i++) {
    CallAdapter<?, ?> adapter = adapterFactories.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(adapterFactories.get(i).getClass().getName());
    }
    builder.append('\n');
  }
  builder.append("  Tried:");
  for (int i = start, count = adapterFactories.size(); i < count; i++) {
    builder.append("\n   * ").append(adapterFactories.get(i).getClass().getName());
  }
  throw new IllegalArgumentException(builder.toString());
}

看看RxJava2CallAdapterFactoryget函数,拿到属于自己的RxJava2CallAdapter

@Override
 public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
   Class<?> rawType = getRawType(returnType);

   if (rawType == Completable.class) {
     // Completable is not parameterized (which is what the rest of this method deals with) so it
     // can only be created with a single configuration.
     return new RxJava2CallAdapter(Void.class, scheduler, isAsync, false, true, false, false,
         false, true);
   }

   boolean isFlowable = rawType == Flowable.class;
   boolean isSingle = rawType == Single.class;
   boolean isMaybe = rawType == Maybe.class;
   if (rawType != Observable.class && !isFlowable && !isSingle && !isMaybe) {
     return null;
   }

   boolean isResult = false;
   boolean isBody = false;
   Type responseType;
   if (!(returnType instanceof ParameterizedType)) {
     String name = isFlowable ? "Flowable"
         : isSingle ? "Single"
         : isMaybe ? "Maybe" : "Observable";
     throw new IllegalStateException(name + " return type must be parameterized"
         + " as " + name + "<Foo> or " + name + "<? extends Foo>");
   }

   Type observableType = getParameterUpperBound(0, (ParameterizedType) returnType);
   Class<?> rawObservableType = getRawType(observableType);
   if (rawObservableType == Response.class) {
     if (!(observableType instanceof ParameterizedType)) {
       throw new IllegalStateException("Response must be parameterized"
           + " as Response<Foo> or Response<? extends Foo>");
     }
     responseType = getParameterUpperBound(0, (ParameterizedType) observableType);
   } else if (rawObservableType == Result.class) {
     if (!(observableType instanceof ParameterizedType)) {
       throw new IllegalStateException("Result must be parameterized"
           + " as Result<Foo> or Result<? extends Foo>");
     }
     responseType = getParameterUpperBound(0, (ParameterizedType) observableType);
     isResult = true;
   } else {
     responseType = observableType;
     isBody = true;
   }

   return new RxJava2CallAdapter(responseType, scheduler, isAsync, isResult, isBody, isFlowable,
       isSingle, isMaybe, false);
 }

我们在拿到ok3的response之后转换为我们需要的类型通过callAdapter的adapter函数,看下RxJava2CallAdapter

@Override public Object adapt(Call<R> call) {
   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;
   }

   if (scheduler != null) {
     observable = observable.subscribeOn(scheduler);
   }

   if (isFlowable) {
     return observable.toFlowable(BackpressureStrategy.LATEST);
   }
   if (isSingle) {
     return observable.singleOrError();
   }
   if (isMaybe) {
     return observable.singleElement();
   }
   if (isCompletable) {
     return observable.ignoreElements();
   }
   return observable;
 }

解析看responseConverter,ServiceMthon.createResponseConverter()–>retrofit.responseBodyConverter–>retrofit.nextResponseBodyConverter()

/**
   * Returns a {@link Converter} for {@link ResponseBody} to {@code type} from the available
   * {@linkplain #converterFactories() factories} except {@code skipPast}.
   *
   * @throws IllegalArgumentException if no converter available for {@code type}.
   */
  public <T> Converter<ResponseBody, T> nextResponseBodyConverter(Converter.Factory skipPast,
      Type type, Annotation[] annotations) {
    checkNotNull(type, "type == null");
    checkNotNull(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;
      }
    }

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

看看GsonConverterFactory

/**
 * A {@linkplain Converter.Factory converter} which uses Gson for JSON.
 * <p>
 * Because Gson is so flexible in the types it supports, this converter assumes that it can handle
 * all types. If you are mixing JSON serialization with something else (such as protocol buffers),
 * you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this instance}
 * last to allow the other converters a chance to see their types.
 */
public final class GsonConverterFactory extends Converter.Factory {
  /**
   * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
   * decoding from JSON (when no charset is specified by a header) will use UTF-8.
   */
  public static GsonConverterFactory create() {
    return create(new Gson());
  }

  /**
   * Create an instance using {@code gson} for conversion. Encoding to JSON and
   * decoding from JSON (when no charset is specified by a header) will use UTF-8.
   */
  public static GsonConverterFactory create(Gson gson) {
    return new GsonConverterFactory(gson);
  }

  private final Gson gson;

  private GsonConverterFactory(Gson gson) {
    if (gson == null) throw new NullPointerException("gson == null");
    this.gson = gson;
  }

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

  @Override
  public Converter<?, RequestBody> requestBodyConverter(Type type,
      Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
    TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
    return new GsonRequestBodyConverter<>(gson, adapter);
  }
}

通过工程得到GsonResponseBodyConverter

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
  private final Gson gson;
  private final TypeAdapter<T> adapter;

  GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
    this.gson = gson;
    this.adapter = adapter;
  }

  @Override public T convert(ResponseBody value) throws IOException {
    JsonReader jsonReader = gson.newJsonReader(value.charStream());
    try {
      return adapter.read(jsonReader);
    } finally {
      value.close();
    }
  }
}

当然请求和GsonResponseBodyConverter类似,也是通过工厂来生成。

总结:

  1. 动态代理实现接口函数调用的拦截
  2. 通过返回类型来和CallAdapter.Factory遍历对比调用get函数拿到对应于的callAdapter,然后通过callAdapter.adapter函数来进行数据转换
  3. 通过返回类型来和Converter.Factory遍历对比调用responseBodyConverterrequestBodyConverter函数拿到对应于的Converter,然后通过Converter.convert函数来进行请求数据或者responseBody的数据转换
  4. 参数解析的时候判断很多,根据你的参数不同实例不同的ParameterHandler,请求的时候通过ParameterHandler组装数据

参考链接: retrofit源码

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Retrofit源码分析

    用户1907613
  • Retrofit 源码分析初探

    现如今,Android开发中,网络层Retrofit+Okhttp组合好像已成标配,身为技术人员,这么火的框架当然得一探究竟,不为装逼,纯粹是为了充电而已。

    砸漏
  • Retrofit之OKHttpCall源码分析

    看到这几个方法有没有很熟悉,没错,几乎和Okhttp的Call方法一模一样,我们看下okhttp的call接口:

    砸漏
  • Android面试刨根问底之常用源码篇(二):OkHttp, Retrofit,自定义View源码分析总结

    由于篇幅原因拆分成两个部分分享,上一篇讲解了前面三个方面,今天讲剩下的三个部分,之后的还会持续更新。

    Android技术干货分享
  • 源码分析Retrofit请求流程

    Retrofit 是 square 公司的另一款广泛流行的网络请求框架。前面的一篇文章《源码分析OKHttp执行过程》已经对 OkHttp 网络请求框架有一个大...

    阳仔
  • 浅谈Retrofit 源码

    现在的项目界面都是按iOS的风格,虽然界面无法发挥出我们大Android的风格,网络框架动不动就是mvp+ okhttp +retrofit+rxjava,m...

    用户1337002
  • Retrofit源码模拟

    如果要进行网络请求,你可能会这样写一个简单的OKHttp请求 public class CallExector { public static fin...

    我就是马云飞
  • 源码阅读--Retrofit

    提莫队长
  • 【Android】Retrofit2.0源码解析

    Gavin-ZYX
  • 不懂网络组件?这一次爱奇艺大佬带你深度分析OkHttp源码与Retrofit封装,彻底了解!

    我们项目当中的每个app都需要用到网络和服务器进行交互,在Android项目开发中使用HTTP协议完成通信的话,基本上都要用到OkHttp或者Retrofit。

    Android技术干货分享
  • 从架构角度看Retrofit的作用、原理和启示

    前言 Retrofit是squareup公司的开源力作,和同属squareup公司开源的OkHttp,一个负责网络调度,一个负责网络执行,为Android开发者...

    我就是马云飞
  • 重温Retrofit源码,笑看协程实现

    最近回归看了一下Retrofit的源码,主要是因为项目接入了协程,所以想研究一下Retorift是如何支持协程的。Retrofit是在Version 2.6.0...

    Rouse
  • 源码解析: Retrofit2.5

    Retrofit是Square公司开发的一款针对Android网络请求的框架,遵循Restful设计风格,我们查看 invoke 可以发现:底层基于OkHttp...

    小木箱
  • 抛开理论,从实践中剖析Rertrofit原理

    Retrofit用法和介绍的文章实在是多的数不清,也有很多介绍其内部原理的,但是看过之后,还是让很多人云里雾里, 本篇文章旨在通过自我实现一个自定义的Retro...

    开发者技术前线
  • Android技能树 — 网络小结(7)之 Retrofit源码详细解析

    介于自己的网络方面知识烂的一塌糊涂,所以准备写相关网络的文章,但是考虑全部写在一篇太长了,所以分开写,希望大家能仔细看,最好可以指出我的错误,让我也能纠正。

    青蛙要fly
  • Android |《看完不忘系列》之Retrofit

    嗨,我是哈利迪~《看完不忘系列》将以从树干到细枝的思路分析一些技术框架,本文将对开源项目Retrofit进行介绍。

    Holiday
  • Retrofit--使用Retrofit时怎样去设置OKHttp

    ? 投稿作者:黄海杰 原文链接:http://blog.csdn.net/lyhhj/article/details/51388147 特别声明:本文为黄海...

    非著名程序员
  • Retrofit--使用Retrofit时怎样去设置OKHttp

    版权声明:本文为博主原创文章,转载请标明出处。 https://blog.csdn.net/lyhhj/article/details/51...

    Hankkin
  • Retrofit网络请求库应用02——json解析

    PS:上一篇写了Retrofit网络请求库的简单使用,仅仅是获取百度的源码,来证明连接成功,这篇讲解如何解析JSON数据,该框架不再是我们之前自己写的那样用Js...

    cMusketeer

扫码关注云+社区

领取腾讯云代金券