Retrofit源码笔记

2018-12-10  本文已影响0人  ewinddc

Retrofit是一款java平台的http client工具,常用于Android。主要基于OkHttp做应用层封装,把http域名转换成java方法,可以自动转换json结果为javabean。github链接官方教程

Retrofit turns your HTTP API into a Java interface.

简单使用流程介绍:

  1. 先构建okhttpclient
  2. Builder模式构建Retrofit
  3. 编写interface,通过注解写域名,把http请求转化为java方法
  4. Retrofit#createService创建实例,返回一个Call
  5. call.enqueue(callback)
  6. callback接收java bean结果

构建OkHttpClient

构建Retrofit

Builder

  interface Factory {
    Call newCall(Request request);
  }
public interface Converter<F, T> {
  T convert(F value) throws IOException;

  /** Creates {@link Converter} instances based on a type and target usage. */
  abstract class Factory {
    //ResponseBody converter的工厂,这个converter负责ReponseBody和bean的转换
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }
    //RequestBody converter的工厂,这个converter用于RequestBody和bean的转换,一般是@Body,@Part,@PartMap
    public Converter<?, RequestBody> requestBodyConverter(Type type,
        Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
      return null;
    }

    //负责string和bean的转换,一般是@Field,@Header,@Path,@Query以及它们对应的map注解
    public Converter<?, String> stringConverter(Type type, Annotation[] annotations,
        Retrofit retrofit) {
      return null;
    }
  }
}

converterFactory需要显式指定,使用fastjson或者gson对应的converter即可,具体可参考Retrofit的wiki

public interface CallAdapter<R, T> {
  Type responseType();

 T adapt(Call<R> call);

  abstract class Factory {
    
    public abstract CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,
        Retrofit retrofit);

    protected static Type getParameterUpperBound(int index, ParameterizedType type) {
      return Utils.getParameterUpperBound(index, type);
    }

    protected static Class<?> getRawType(Type type) {
      return Utils.getRawType(type);
    }
  }
}


//Call如何在Observable运行
  protected void subscribeActual(Observer<? super Response<T>> observer) {
    // Since Call is a one-shot type, clone it for each new observer.
    Call<T> call = originalCall.clone();
    CallDisposable disposable = new CallDisposable(call);
    observer.onSubscribe(disposable);
    if (disposable.isDisposed()) {
      return;
    }

    boolean terminated = false;
    try {
      Response<T> response = call.execute();
      if (!disposable.isDisposed()) {
        observer.onNext(response);
      }
      if (!disposable.isDisposed()) {
        terminated = true;
        observer.onComplete();
      }
    } catch (Throwable t) {
      Exceptions.throwIfFatal(t);
      if (terminated) {
        RxJavaPlugins.onError(t);
      } else if (!disposable.isDisposed()) {
        try {
          observer.onError(t);
        } catch (Throwable inner) {
          Exceptions.throwIfFatal(inner);
          RxJavaPlugins.onError(new CompositeException(t, inner));
        }
      }
    }
  }

创建请求interface

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
@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);

createService

 public <T> T create(final Class<T> 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 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);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
  }
 @Override ReturnT invoke(Object[] args) {
    return callAdapter.adapt(
        new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
  }

call#enqueue(callback)

public interface Callback<T> {
  void onResponse(Call<T> call, Response<T> response);

  void onFailure(Call<T> call, Throwable t);
}

reference

上一篇 下一篇

猜你喜欢

热点阅读