Android Retrofit基本使用及原理

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_45258969/article/details/97006164

Retrofit其实我们可以理解为OkHttp的加强版,它也是一个网络加载框架。底层是使用OKHttp封装的。

Retrofit注解说明

请求方法

image

请求参数

image

基本使用

1、在build.gradle内导入依赖库

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0' // 用Gson解析json的转换器

2、申请网络权限

<uses-permission android:name="android.permission.INTERNET"/>

3、根据接口数据创建实体类,此处略。

4、创建ApiService.java类

/**
 * Created by hzy on 2019/1/10
 **/
public interface ApiService {

    /**
     * 获取banner图
     * @return
     */
    @GET("banner/json")
    Call<BannerList> getBanner();

    @GET("article/list/{page}/json")
    Call<KnowledgeSystem> getKnowledgeSystem(@Path("page") int page, @Query("cid") int cid);

}

此处为鸿洋开发接口:http://www.wanandroid.com/blog/show/2

5、get请求 创建retrofit,并获取数据

        //1、创建retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Urls.BASIC_URL)
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //2、用retrofit加工出对应的接口实例对象
        ApiService api = retrofit.create(ApiService.class);
        //3、获取适配转换Call对象
        Call<KnowledgeSystem> call = api.getKnowledgeSystem(1,60);
        //4、调用call.enqueue方法获取数据
        call.enqueue(new Callback<KnowledgeSystem>() {
            @Override
            public void onResponse(Call<KnowledgeSystem> call, Response<KnowledgeSystem> response) {
                Log.d("Response--response", response.body().toString());
            }

            @Override
            public void onFailure(Call<KnowledgeSystem> call, Throwable t) {
                Log.d("Response--onFailure", t.toString());
            }
        });

6、post请求 创建retrofit,并获取数据

ApiService.java

    @FormUrlEncoded
    @POST("user/login")
    Call<Object> postLogin(@Field("username") String username, @Field("password") String password);
        //1、创建retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Urls.BASIC_URL)
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        //2、用retrofit加工出对应的接口实例对象
        ApiService api = retrofit.create(ApiService.class);
        //3、获取适配转换Call对象
        Call<Object> call=api.postLogin("4645674677645@qq.com","123456");
        //4、调用call.enqueue方法获取数据
        call.enqueue(new Callback<Object>() {
            @Override
            public void onResponse(Call<Object> call, Response<Object> response) {
                Log.d("Response--response", response.body().toString());
            }

            @Override
            public void onFailure(Call<Object> call, Throwable t) {
                Log.d("Response--onFailure", t.toString());
            }
        });

Retrofit2实现原理

Retrofit2的build()方法

    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()这个方法里面会创建一个OkHttpClient(),当然你可以在外面传递进入,比如像下面代码一样:

OkHttpClient okHttpClient = new OkHttpClient();
Retrofit retrofit = new Retrofit.Builder().baseUrl("www.xxxx.com").client(okHttpClient).build();

接下来我们来看看create方法的实现:

  @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
  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() {
          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);
          }
        });
  }

调用create()方法会返回一个范型T,我们这里是ApiService对象,当ApiService调用自身方法的时候,因为它运用了动态代理,所以会调用invoke方法。invoke方法内先将method转换为ServiceMethod对象,再将serviceMethod和args对象传入OkHttpCall构造方法中,返回一个OkHttpCall,最后将OkHttpCall传入adapt方法,最后返回一个Call对象。

private final Map<Method, ServiceMethod> serviceMethodCache = new LinkedHashMap<>();
 ServiceMethod loadServiceMethod(Method method) {
    ServiceMethod result;
    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
        result = new ServiceMethod.Builder(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

loadServiceMethod方法通过method去serviceMethodCache集合对象中获取缓存。那ServiceMethod究竟是一个什么东东?先看看ServiceMethod中方法的实现。

ServiceMethod.Builder

ServiceMethod(Builder<T> builder) {
    this.callFactory = builder.retrofit.callFactory();
    this.callAdapter = builder.callAdapter;
    this.baseUrl = builder.retrofit.baseUrl();
    this.responseConverter = builder.responseConverter;
    this.httpMethod = builder.httpMethod;
    this.relativeUrl = builder.relativeUrl;
    this.headers = builder.headers;
    this.contentType = builder.contentType;
    this.hasBody = builder.hasBody;
    this.isFormEncoded = builder.isFormEncoded;
    this.isMultipart = builder.isMultipart;
    this.parameterHandlers = builder.parameterHandlers;
  }

在ServiceMethod的构造参数里面发现,包含了一些请求的信息,如baseUrl,httpMethod,hasBody ,isFormEncoded 等信息。

public ServiceMethod build() {
      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?");
      }
      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);
      }

     //省略部分代码。。。

      return new ServiceMethod<>(this);
    }

build()方法中,会创建callAdapter,也会循环调用parseMethodAnnotation(annotation),此外如果hasBody==false并且isMultipart或者isFormEncoded为true,那么将会抛出methodError的错误,这也验证了之前的结论:如果定义的java接口参数为空,那么@FormUrlEncoded以及@Multipart需要去掉。最后build()方法会返回一个ServiceMethod。

先看看createCallAdapter

private CallAdapter<?> createCallAdapter() {
      Type returnType = method.getGenericReturnType();
      if (Utils.hasUnresolvableType(returnType)) {
        throw methodError(
            "Method return type must not include a type variable or wildcard: %s", returnType);
      }
      if (returnType == void.class) {
        throw methodError("Service methods cannot return void.");
      }
      Annotation[] annotations = method.getAnnotations();
      try {
        return retrofit.callAdapter(returnType, annotations);
      } catch (RuntimeException e) { // Wide exception range because factories are user code.
        throw methodError(e, "Unable to create call adapter for %s", returnType);
      }
    }

在createCallAdapter方法中主要就是获取method类型和注解,最后再调用callAdapter(returnTYpe,annotations),现在进入retrofit的callAdapter(returnType, annotations)方法:

public CallAdapter<?> callAdapter(Type returnType, Annotation[] annotations) {
    return nextCallAdapter(null, returnType, annotations);
 }

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

  //移除处理代码省略。。。

  }

callAdapter方法实际调用的是nextCallAdapter,通过传入的参数去循环在adapterFactories集合里面取出不为null的CallAdapter并返回。

parseMethodAnnotation(annotation):

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);
        if (!Void.class.equals(responseType)) {
          throw methodError("HEAD method must use Void as response type.");
        }
      } else if (annotation instanceof PATCH) {

    //省略部分代码。。。

    }

 private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) {
      if (this.httpMethod != null) {
        throw methodError("Only one HTTP method is allowed. Found: %s and %s.",
            this.httpMethod, httpMethod);
      }
      this.httpMethod = httpMethod;
      this.hasBody = hasBody;

      // 省略部分代码。。。

      this.relativeUrl = value;
      this.relativeUrlParamNames = parsePathParameters(value);
    }

parseMethodAnnotation(annotation)方法里面主要是判断注解的类型,然后分别调用方法对ServiceMethod的成员变量进行赋值。

最后我们来看看ServiceMethod的toRequest方法:

/** Builds an HTTP request from method arguments. */
  Request toRequest(Object... args) throws IOException {
    RequestBuilder requestBuilder = new RequestBuilder(httpMethod, baseUrl, relativeUrl, headers,
        contentType, hasBody, isFormEncoded, isMultipart);

    @SuppressWarnings("unchecked") // It is an error to invoke a method with the wrong arg types.
    ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers;

    //省略部分代码。。。

    for (int p = 0; p < argumentCount; p++) {
      handlers[p].apply(requestBuilder, args[p]);
    }
    return requestBuilder.build();
  }

在toRequest方法中,将处理好的变量通过RequestBuilder封装,最后返回一个HTTP request。看到这里我们大概明白ServiceMethod是拿来做什么的了。大概总结一下:
ServiceMethod接收到传入Retrofit对象和Method对象之后,ServiceMethod通过获得method里面的参数,然后调用各种解析器,最后将处理好的变量赋值给ServiceMethod成员变量,最后在toRequest方法中将这些参数给封装成OkHttp3的一个Request对象。

现在回到Retrofit的create方法中:

OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);

获取serviceMethod之后,会将其作为参数继续封装为OkHttpCall对象;createRawCall会从serviceMethod中拿到Request,并转换为Call。

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

parseResponse方法中会处理接口返回的结果,并调用serviceMethod中的toResponse方法去转换接口请求回来的数据,前面的例子,我们是给Retrofit设置的gson转换,因此这里是使用gson转换成java对象。

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

   //处理返回码,代码省略。。。

    ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
    try {
      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;
    }
  }

  T toResponse(ResponseBody body) throws IOException {
    return responseConverter.convert(body);
  }

通过前面的讲解,我们发现ServiceMethod中封装了接口请求的数据,而OkHttpCall则从ServiceMethod中获得一个Request对象,最后返回一个Call对象,在接口回调之后,通过ServiceMethod中的Converter将接口中的ResponseBody 转换成Java对象。

拿到okHttpCall之后,将它传入adapt方法:我们在来看看Retrofit的create方法。

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

          @Override public Object invoke(Object proxy, Method method, Object... args)
              throws Throwable {
            // //省略部分代码。。。。
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

重点看方法里面的两行有return的代码,调用create方法的时候返回一个泛型T,我们这里是PersonalProtocol,当我们调用PersonalProtocol的getPersonalListInfo的时候会通过动态代理,并返回serviceMethod.callAdapter.adapt(okHttpCall)也就是一个Call对象:

 @Override public <R> Call<R> adapt(Call<R> call) {
        return call;
 }

于是就有了之前的代码:

Call<Response<PersonalInfo>> call = personalProtocol.getPersonalListInfo(12);
 call.enqueue(new Callback<Response<PersonalInfo>>() {
            @Override
            public void onResponse(Call<Response<PersonalInfo>> call, Response<Response<PersonalInfo>> response) {
                //数据请求成功
            }

            @Override
            public void onFailure(Call<Response<PersonalInfo>> call, Throwable t) {
                //数据请求失败
            }
        });

分析到这里,基本的原理就分析完了。

最后

如果你看到了这里,觉得文章写得不错就给个呗?如果你觉得那里值得改进的,请给我留言。一定会认真查询,修正不足。谢谢。

希望读到这的您能转发分享关注一下我,以后还会更新技术干货,谢谢您的支持!

转发+点赞+关注,第一时间获取最新知识点

Android架构师之路很漫长,一起共勉吧!

展开阅读全文

没有更多推荐了,返回首页