首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >从源码梳理Retrofit网络请求过程

从源码梳理Retrofit网络请求过程

作者头像
coderZhen
发布2018-06-28 17:03:05
5220
发布2018-06-28 17:03:05
举报
文章被收录于专栏:Android开发经验Android开发经验

通过定义一个接口,在方法上加入相关注解,Retrofit框架就可以把它解析成对应的网络请求,使用非常方便,记录下从源码角度看这个过程是怎么实现的。

一 Retrofit的引入

在Android Studio中引入Retrofit非常方便,目标最新版本是2.3,在app-build文件-dependencies节点下加入以下依赖即可:

    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'

    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.1.0'

这里引入最后的两个依赖是为了与rx结合使用,可以先不加。

二 Retrofit是如何通过接口来生成网络请求的

首先,我们定一个接口,同时声明一个方法:

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

这里我们要请求github某个用户下的所有仓库。

调用很简单:

 ApiService apiService = retrofit.create(ApiService.class);
 Call<List<Repo>> solveBus = apiService.listRepos("SolveBugs");
 solveBus.enqueue(new Callback<List<Repo>>() {
           @Override
           public void onResponse(Call<List<Repo>> call,   Response<List<Repo>> response) {
                List<Repo> repoList = response.body();
                StringBuilder sb = new StringBuilder();
                for (Repo repo : repoList) {
                    sb.append(repo.getName());
                    sb.append("\n");
                }
                textView.setText(sb.toString());
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {

            }
  });
1.首先来看retrofit. create()方法

屏幕快照 2017-09-25 下午4.01.15.png

这个方法返回的是一个动态代理对象,当我们用这个对象调用listRepos方法的时候实际上会走到这里的invoke方法,在这个方法里,首先根据接口定义的方法,生成一个ServiceMethod对象,看一下ServiceMethod这个类的注释:

Adapts an invocation of an interface method into an HTTP call.

所以这个类就是一个关于http请求信息的封装。那么是怎么封装的呢? 主要逻辑在loadServiceMethod方法里。

ServiceMethod<?, ?> loadServiceMethod(Method method) {
    ServiceMethod<?, ?> result = serviceMethodCache.get(method);
    if (result != null) return result;

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

逻辑很清晰,首先从缓存里取,如果没有的传入method(即我们声明的接口中的方法对象),通过build方法生成一个,然后放入缓存。 在build方法中,遍历method的所有注解,来取出其中的信息,比如请求方法以及地址等:

for (Annotation annotation : methodAnnotations) {
       parseMethodAnnotation(annotation);
}

屏幕快照 2017-09-25 下午4.12.36.png

拿到封装好的ServiceMethod对象后,构造一个OkHttpCall对象,以便与进行真正的网络请求(Retrofit基于OkHttp实现网络请求)。

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

回到最开始调用的地方:

这里真正调用的是okHttpCall对象的enqueue方法,这里进行的就是具体的网络请求操作了。

代码逻辑其实还是比较清晰的,主要是用到了很多设计模式,所以看起来可能有些费劲,里边儿的细节还要细细研究。(逃,继续看源码去)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.09.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一 Retrofit的引入
  • 二 Retrofit是如何通过接口来生成网络请求的
    • 1.首先来看retrofit. create()方法
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档