Retrofit源码模拟

时间:2022-04-26
本文章向大家介绍Retrofit源码模拟,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

如果要进行网络请求,你可能会这样写一个简单的OKHttp请求

public class CallExector {

    public static final MediaType JSON

            = MediaType.parse("application/json; charset=utf-8");


    private static OkHttpClient client = new OkHttpClient();


    public static String post(String url, String json) throws IOException {

        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()

                .url(url)

                .post(body)

                .build();

        Response response = client.newCall(request).execute();

        return response.body().string();

    }

}

这个代码是最简单的一个网络请求,我们来分析下

client使用默认的okhttpclient对象,我们在调用方法的时候如果想要定制client对象,这里不能写死在里面,看来不能用静态,或许可以使用外界引用 Post方法太抽象,每次调用该方法不能区分究竟是干什么请求,如果能够指定方法名就好了 传入参数太单一,如果我想任意传入类型,都能有一个转换类来最终转化为string参数,这就省了我好多事 返回类型也是单一,我是否可以考虑和3一样 鉴于以上种种问题,我们可以考虑在callexector内部附加一些额外参数来满足我们的要求 callexector第一需要一个okhttpclient对象实现定制与网络请求,第二需要一个对象来处理自定义的方法,解析并实现细节,第三需要一个对象来将传入类型转化为请求的数据,第四需要将请求的数据转化为想要的类型 看来至少需要4个变量来实现,这4个变量也不一定必须要,这时我们想到了builder,可以这样写:

New Callexector.builder().setXXX.build();

定制okhttpclient

本文旨在模拟Retrofit的源码

public class CallExector {

    public static final MediaType JSON

            = MediaType.parse("application/json; charset=utf-8");

    private OkHttpClient client = new OkHttpClient();

    public CallExector(OkHttpClient client) {

        this.client = client;

    }

public static final class Builder {

    private OkHttpClient client;

    public Builder setClient(OkHttpClient client) {

        this.client = client;

        return this;

    }


    public CallExector build(){

        if(this.client == null)

            client = new OkHttpClient();

        return new CallExector(client);

    }

}


    public static String post(String url, String json) throws IOException {

        RequestBody body = RequestBody.create(JSON, json);

        Request request = new Request.Builder()

                .url(url)

                .post(body)

                .build();

        Response response = client.newCall(request).execute();

        return response.body().string();

    }

}

这样就可以定制你的okhttpclient:

CallExector exector = new CallExector.Builder()        
   .setClient(new OkHttpClient())        
   .build();

外部定制接口方法,Callexector来代理实现自定义接口具体方法

编写你的接口:

public interface MethodDeclear {

    String login(String url, String json);

    String register(String url, String json);

    String logout(String url, String json);

}

使Callexector代理实现该接口的具体请求:

public <T> T create(Class<T> service){

    if(!service.isInterface()) {

        throw new RuntimeException("service must be a interface");

    }

    return (T) Proxy.newProxyInstance(service.getClassLoader(),

            new Class<?>[] { service },methodHandler);

}

Proxy.newProxyInstance前面2个固定值,后面第三个参数是真正需要实现该接口方法的内容,我们可以看如下值:

private InvocationHandler methodHandler = new InvocationHandler() {

    /**

     * 接口方法调用的具体实现

     * @param proxy 代理类

     * @param method 代理方法

     * @param args 方法参数

     * @return 方法的返回类型 string

     * @throws Throwable

     */

    @Override

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if (method.getDeclaringClass() == Object.class) {

            return method.invoke(this, args);

        }

        return execteMethod(method,args);

    }

};

在进行一系列的判断之后,最终进入execteMethod(method,args);方法接口的具体实现,这个方法很有意思,可以得到很多数据

private String execteMethod(Method method, Object[] args)throws IOException {

    //默认参数一为uri

    String uri = (String) args[0];

    //默认参数二为请求参数

    String params = (String) args[1];

    return post(uri,params);

}

String post(String url, String json) throws IOException {

    RequestBody body = RequestBody.create(JSON, json);

    Request request = new Request.Builder()

            .url(url)

            .post(body)

            .build();

    Response response = client.newCall(request).execute();

    return response.body().string();

}

execteMethod只是简单实现,没有做任何判断,我们假设实现一个request请求,用的client是builder定制的client,这样我们已经实现问题1和2的功能了

鉴于以上方法,现在我们发现,定义接口虽然可以自定义接口命名,但是真正在代理实现接口的时候并不关心接口名,只关心其接口的入参和出参,而且固定了参数类型为String类型。下面我们还需要将参数类型转化,自定自定义类型转化,比如修改传入参数,将object对象转化为json字符串,修改传出参数,将responsebody转化为我们想要的类型

类型转换类convert

定义一个转化接口:

public abstract class ParamConverter<I,O> {

    abstract RequestBody convertRequest(I request);

    abstract O convertResponse(ResponseBody response);

}

泛型I代表输入 泛型O代表输出

我们知道,在使用okhttp的时候,request会被构造成RequestBody,response返回会由ResponseBody返回,也就是在使用原先接口post传入参数最终转化为RequestBody,ResponseBody,所以我们使用自定义convert转化,将不管方法传入什么类型的参数,那么我们自由实现入参出参的转化。

由于MethodDeclear 默认使用的方法post(String url, String json)在execteMethod(Method method, Object[] args)方法里面最终是转化为RequestBody,ResponseBody。所以我们可以实现该接口并添加自由类型转化的功能,我们稍微改造一下方法实现,如下:

private Object execteMethod(Method method, Object[] args)throws IOException {

        //默认参数一为uri

        String uri = (String) args[0];

        //默认参数二为请求参数

//        String params = (String) args[1];

//        RequestBody body = RequestBody.create(JSON, params);

        RequestBody body = paramConverter.convertRequest(args[1]);

        return post(uri,body);

    }

    Object post(String uri,RequestBody body) throws IOException {

        Request request = new Request.Builder()

                .url(uri)

                .post(body)

                .build();

        ResponseBody response = client.newCall(request).execute().body();

        return paramConverter.convertResponse(response);

    }

那么针对以上方法的适配,要将传入类型转化该怎么实现呢?如下:

public class DefaultConvert extends ParamConverter<String,String>{

    public static final MediaType JSON

            = MediaType.parse("application/json; charset=utf-8");

    @Override

    RequestBody convertRequest(String request) {

        RequestBody body = RequestBody.create(JSON, request);

        return body;

    }

    @Override

    String convertResponse(ResponseBody response) {

        return response.string();

}

这样是不是就能将任何传入参数使用ParamConverter转化为requestBody,将responseBody转化为任何想要的结果类型!Square真是喜欢泛型转化,不管RXJAVA还是Retrofit都有泛型转化

到这里你以为结束了吗?NO,NO,NO,下面才是重点 我们看以上代码,这样自己定义接口动态代理实现的方式也真是挺高端了,但是与retrofit功能相比还有一个地方不同,我们在定义接口的时候直接返回结果了,这样我们假如想要得到call对象然后必要时候想取消网络怎么办,一想到这里我就害怕,万一Boss提出这样的要求我没法实现是不是要被杀了祭天? 嘿嘿 ~ 不存在的。我们还需要对此进行改造哦~ 上代码,我们现在修改的接口

public interface MethodDeclear {  
  CallImpler<String> post(String url, String json);
}

CallImpler返回类是一个Call的包装类,里面泛型参数是请求返回类型,这里需要之前的转换类convert进行转化 CallImpler类只是重复了call接口的方法,修改enqueue方法回掉,添加回掉参数的转化,这样做一个包装,保证接口灵活性

public class CallImpler<T>{

    private Call call;

    private ParamConverter<Object,T> paramConverter;

    public CallImpler(Call call, ParamConverter<Object, T> paramConverter) {

        this.call = call;

        this.paramConverter = paramConverter;

    }

    Request request(){

        return call.request();

    }

    Response execute() throws IOException{

        return call.execute();

    }

    void cancel(){

        call.cancel();

    }

    boolean isExecuted(){

        return call.isExecuted();

    }

    boolean isCanceled(){

        return call.isCanceled();

    }


    public void enqueue(final CallBack<T> responseCallback){

        call.enqueue(new okhttp3.Callback() {

            @Override

            public void onFailure(Call call, IOException e) {

                responseCallback.onFailure(CallImpler.this,e);

            }


            @Override

            public void onResponse(Call call, Response response) throws IOException {

                responseCallback.onResponse(CallImpler.this,paramConverter.convertResponse(response.body()));

            }

        });

    }

}

paramConverter用来转化responseBody,前面讲过可以定制的哦~

既然我们定义的接口返回参数修改了,那么具体方法的实现体也需要修改了。看之前的方法execteMethod:

转化入参 同步网络请求 转化出参 这个方法把call对象都写隐藏了,我们需要提取call对象,并且跳过2,让2主动调用,13预先设定好 那么这样修改:

private Object execteMethod(Method method, Object[] args)throws IOException {

        //默认参数一为uri

        String uri = (String) args[0];

        //默认参数二为请求参数

//        String params = (String) args[1];

//        RequestBody body = RequestBody.create(JSON, params);

        RequestBody body = paramConverter.convertRequest(args[1]);

        return post(uri,body);

    }

    Object post(String uri,RequestBody body) throws IOException {

        Request request = new Request.Builder()

                .url(uri)

                .post(body)

                .build();

        return new CallImpler(client.newCall(request),paramConverter);//paramConverter.convertResponse(response);

    }

execteMethod方法post返回call的包装类CallImpler 这样修改,我们就可以得到call对象了,实现call的请求,查询,取消等等操作~

到这里应该差不多了吧,但是比起Retrofit还是差一些,哪里呢,Retrofit的返回类型包装类(我们这里是CallImpler)也是可以转化的哦,那么又是泛型转化!其实我都转晕了,光看不行,直接秀操作:

我需要把CallImpler转化为自定义类,那么写一个类,他的传入类型为CallImpler类型,出去类型要是泛型,为止类型,自由转化,自由实现:

public abstract class CallAdapter<T,R> { 
   abstract T adapt(CallImpler<R> call);
}

这样应该可以吧?我们把他加入CallExector类,这样实现返回类型call的包装与定制化~ 上builder代码

public static final class Builder {

    private OkHttpClient client;

    private ParamConverter paramConverter;

    private CallAdapter callAdapter;

    public Builder setClient(OkHttpClient client) {

        this.client = client;

        return this;

    }


    public Builder setParamConverter(ParamConverter paramConverter) {

        this.paramConverter = paramConverter;

        return this;

    }


    public Builder setCallAdapter(CallAdapter callAdapter) {

        this.callAdapter = callAdapter;

        return this;

    }


    public CallExector build(){

        if(this.client == null)

            client = new OkHttpClient();

        if(this.paramConverter == null)

            paramConverter = new DefaultConvert();

        if(this.callAdapter == null)

            this.callAdapter = new DefaultCallAdapter();

        return new CallExector(client,paramConverter,callAdapter);

    }

}

默认的calladapter传入CallImpler<T>我们默认直接返回,不做操作啦,要转化的请在adapt方法中将CallImpler<T>转化为自定义类吧,任你怎么玩,就是别玩坏了~

下面我们来总结一下用法啦:

CallExector exector = new CallExector.Builder()

        .setClient(new OkHttpClient())

        .setParamConverter(new DefaultConvert())

        .setCallAdapter(new DefaultCallAdapter())

        .build();

MethodDeclear interf = exector.create(MethodDeclear.class);

CallImpler<String> caller = interf.post("url","args");

caller.enqueue(new CallBack<String>() {

    @Override

    public void onResponse(CallImpler<String> call, String response) {

    }


    @Override

    public void onFailure(CallImpler<String> call, Throwable t) {

    }

});

怎样,是不是和Retrofit一模一样~ 学习上面的内容,你必须要学到2点内容

1.代理反射,即自定义一个接口,由Proxy代理实现方法[Proxy.newProxyInstance(ClassLoader loader,Class<?>[] interfaces,InvocationHandler h)] 2.泛型自由转化,由一个类型转化为另一个类型

如果掌握这2点,以上基本完全理解了吧~ 这也对得起你看了这么久嘛。别说你的手指正落在滚轮上! Ps: 想看kotlin文件转化请使用AS 3.0,对文件使用ctrl+alt+shift+K~

主要类:

CallExector builder模式 -> 同Retrofit类 okhttpClient -> okhttp3.Call.Factory callFactory; ParamConvert -> List<Converter.Factory> converterFactories; CallAdapter<T,R> -> Retrofit.List<CallAdapter.Factory> adapterFactories CallImpler<T> -> Retrofit.Call<T> CallBack<T> -> Retrofit.CallBack<T> MethodDeclear:自定义接口通用

Sources源代码

这就是Retrofit的具体简单实现,当然了,有人估计会问那么多注解annotation去哪里了,这个嘛,其实annotation人家也是定义好了,然后再代理方法里面区分判断的,就像我们也是不依赖接口方法名一样,但是咱们可是定死了参数个数,他用注解就可以避免这些问题,除了annotation,以上便是实现原理和模拟,下面附上Retrofit的annotation解析的位置

retrofit2.ServiceMethod<R, T>.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);

        if (!Void.class.equals(responseType)) {

          throw methodError("HEAD method must use Void as response type.");

        }

      } 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("@Headers annotation is empty.");

        }

        headers = parseHeaders(headersToParse);

      } else if (annotation instanceof Multipart) {

        if (isFormEncoded) {

          throw methodError("Only one encoding annotation is allowed.");

        }

        isMultipart = true;

      } else if (annotation instanceof FormUrlEncoded) {

        if (isMultipart) {

          throw methodError("Only one encoding annotation is allowed.");

        }

        isFormEncoded = true;

      }

}

其实这部分我们也可以实现,请自行移步其他大神java注解篇~