博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
优雅地调用接口--手把手带你从0到1实现retrofit框架
阅读量:6630 次
发布时间:2019-06-25

本文共 12006 字,大约阅读时间需要 40 分钟。

retrofit作为http请求的接口框架而被众人熟知道,它独特且优雅的接口使用习惯被无数的程序员所认可。

介绍

A type-safe HTTP client for Android and Java

Retrofit是一个基于AOP思想,对RestfulApi注解进行动态代理的网络框架。

public interface GitHubService {  @GET("users/{user}/repos")  Call
> listRepos(@Path("user") String user);}Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com/") .build();GitHubService service = retrofit.create(GitHubService.class);

我们的JT框架

JTHttpClient                .create()                .setSecLevel(JtRequest.NORMAL)                .url(Urls.index_V)                .build()                .post(HomeModule.class)                .subscribe(new JtSingObserver
(this) { @Override public void onSuccess(HomeModule homeModule) { if (homeModule.header.app_login_status == 0) { JTApi.get().logout(); } sHomeModule = homeModule; mHomeModule.setValue(homeModule); } @Override public void onError(Throwable e) { sHomeModule = null; mHomeModule.setValue(null); UIUtil.INSTANCE.showExceptionMsg(e); } });

我在深思熟虑中打造的JT框架虽然简单易用性和性能上其实已经很优秀,但是经过我再一次的深思熟虑觉得依然存在着一些问题。

  • 模板类代码太多
  • 泛型传递太频发(两次)
  • 链式的调用过程某种程度意味效率的低下(选择遗忘的太多)

Retrofit的实现过程

retrofit的主要技术细节包括:

1.接口的实例化
2.获取泛型的返回值type(数据的解析和实例化观察者需要)
3.获取Method之后通过反射获取方法注解和参数注解

我们忽略了一些AOP编程的细节,而是主要去关注一个注解方法对象(Method)的解析过程。

retrofit将Method对象解析成对应http request;将request的参数给下层的网络适配器adapter(可以认为是OkhttpAdapter),适配器调用自身execute方法,调用成功后通过线程分发器发送到对应的线程。至此,完成了retrofit对网络的完整的抽象。

img_bf4c3513589ee77bd5028681040f79f0.png
retrofit_stay.png
public 
T create(final Class
service) {//函数的入口,实例化接口对象 Utils.validateServiceInterface(service);//检查service合法性 if (validateEagerly) { eagerlyValidateMethods(service); } //动态代理实例化对象 return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class
[] {service}, new InvocationHandler() { @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. //解析method注解并交给call对象(网络执行者,默认okhttpclient) // 触发http请求的方法。invoke会返回Call对象,调用该对象的方法即可完成网络请求 return loadMethodHandler(method).invoke(args); } }); } MethodHandler loadMethodHandler(Method method) { MethodHandler handler; synchronized(methodHandlerCache) {//查看静态缓存区,是否有对应method可用,加快执行的速度 handler = methodHandlerCache.get(method); if (handler == null) { //创建MethodHandler对象, //该对象用来管理 // requestFactory请求构造器, // callFactory(http执行栈默认OkHttpClient), // callAdapter回调适配器(用于线程的分发), // responseConverter内容转换器 // 可以认为一种接口method与http请求过程的媒介 // new MethodHandler(retrofit.callFactory(), requestFactory, callAdapter,responseConverter); handler = MethodHandler.create(this, method); methodHandlerCache.put(method, handler); } } return handler; } static MethodHandler create(Retrofit retrofit, Method method) { //创建callAdapter, callAdapter是一个可以用来触发网络成功或失败的回调的对象,该方法主要 // 1.查找当前队列中可用的callAdapter // 2.不管有没有查找成功都会获取method返回值(method.getGenericReturnType())的泛型type // 3.验证合法性 CallAdapter
callAdapter = createCallAdapter(method, retrofit); Type responseType = callAdapter.responseType(); if (responseType == Response.class || responseType == okhttp3.Response.class) { throw Utils.methodError(method, "'" + Types.getRawType(responseType).getName() + "' is not a valid response body type. Did you mean ResponseBody?"); } //创建responseConverter,这个方法不关注 Converter
responseConverter = createResponseConverter(method, retrofit, responseType); //解析获得请求的参数,创建requestFactory,最为核心且最复杂的方法 // RequestFactory: // private final String method; // private final BaseUrl baseUrl; // private final String relativeUrl; // private final Headers headers; // private final MediaType contentType; // private final boolean hasBody; // private final boolean isFormEncoded; // private final boolean isMultipart; // private final RequestAction[] requestActions; RequestFactory requestFactory = RequestFactoryParser.parse(method, responseType, retrofit); return new MethodHandler(retrofit.callFactory(), requestFactory, callAdapter, responseConverter); } static RequestFactory parse(Method method, Type responseType, Retrofit retrofit) { RequestFactoryParser parser = new RequestFactoryParser(method); Annotation[] methodAnnotations = method.getAnnotations(); //解析method方法的注解annotations[] parser.parseMethodAnnotations(responseType, methodAnnotations); //解析method参数的注解annotations[][],此处是二维数组 parser.parseParameters(retrofit, methodAnnotations); return parser.toRequestFactory(retrofit.baseUrl()); }//该方法用于通过returnType查找对应的callAdapter并获取实例化的callAdapter对象 private static CallAdapter
createCallAdapter(Method method, Retrofit retrofit) { Type returnType = method.getGenericReturnType(); if (Utils.hasUnresolvableType(returnType)) { throw Utils.methodError(method, "Method return type must not include a type variable or wildcard: %s", returnType); } if (returnType == void.class) { throw Utils.methodError(method, "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 Utils.methodError(e, method, "Unable to create call adapter for %s", returnType); } }

JT的实现

主要实现的步骤:

  1. 动态代理实例化接口对象
  2. 在invoke函数中获取被调用的Method对象
  3. 解析并拿到Method中的request参数和返回值泛型的type
//return typeType returnType = method.getGenericReturnType();            if (method.getReturnType() == Single.class) {            } else {                throw new IllegalArgumentException("you must return a type == Single.class");            }            if (returnType instanceof ParameterizedType) {                Type[] actualTypeArguments = ((ParameterizedType) returnType)                        .getActualTypeArguments();                if (actualTypeArguments.length == 1) {                    mReturnType = actualTypeArguments[0];                } else {                    throw new IllegalArgumentException();                }            }//缓存Method的request.builder参数,调用perform方法去注入builderprivate List
requestActionList = new ArrayList<>();
  1. 通过jtclient发送http请求
    5.根据3中的返回值泛型type解析response
    6.最后,通知观察者,处理所订阅的事件
apiService = Proxy.newProxyInstance(service.getClassLoader(),                new Class
[] {service}, new InvocationHandler() { //这个invoke方法会在代理对象的方法中调用,第一个参数就是代理对象 //第二个参数是代理对象调用的方法 //第三个参数方法的参数 @Override public Object invoke(Object proxy, Method method, Object... args) throws Throwable { validateServiceInterface(service); // If the method is a method from Object then defer to normal invocation. if (method.getDeclaringClass() == Object.class) { return method.invoke(this, args); } //调用loadMethodHandler return loadMethodHandler(method).invoke(args); } });Type returnType = method.getGenericReturnType(); if (method.getReturnType() == Single.class) { } else { throw new IllegalArgumentException("you must return a type == Single.class"); } if (returnType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) returnType) .getActualTypeArguments(); if (actualTypeArguments.length == 1) { mReturnType = actualTypeArguments[0]; } else { throw new IllegalArgumentException(); } } MethodHandler(Method method) { if (JTApi.get().isDebug()) { Log.e("MethodHandler", "MethodHandler-method " + method.getName()); } Type returnType = method.getGenericReturnType(); if (method.getReturnType() == Single.class) { } else { throw new IllegalArgumentException("you must return a type == Single.class"); } if (returnType instanceof ParameterizedType) { Type[] actualTypeArguments = ((ParameterizedType) returnType) .getActualTypeArguments(); if (actualTypeArguments.length == 1) { mReturnType = actualTypeArguments[0]; } else { throw new IllegalArgumentException(); } } Annotation[] methodAnnotation = method.getAnnotations(); for (Annotation annotation : methodAnnotation) { if (annotation instanceof Url) { mUrl = ((Url) annotation).value(); } else if (annotation instanceof Security) { security = ((Security) annotation).value(); } } Annotation[][] parameterAnnotations = method.getParameterAnnotations(); if (parameterAnnotations == null || parameterAnnotations.length == 0) { return; } for (Annotation[] annotations : parameterAnnotations) { if (annotations != null && annotations.length != 0) { for (Annotation aMethodAnnotation : annotations) { if (aMethodAnnotation instanceof Field) { Field field = (Field) aMethodAnnotation; requestActionList.add(new FieldRequestAction(field.value())); break; } else if (aMethodAnnotation instanceof FieldMap) { requestActionList.add(new FieldMapRequestAction()); } else if (aMethodAnnotation instanceof Path) { Path path = (Path) aMethodAnnotation; requestActionList.add(new PathRequestAction(path.value())); } } } } } public Object invoke(Object... objects) { JtRequest.Builder builder = JTHttpClient.create().url(mUrl); if (objects != null && objects.length > 0) { if (objects.length != requestActionList.size()) { throw new NullPointerException("url: " + mUrl + "\nrequestActionList length is " + "not equals objects length"); } for (int i = 0; i < requestActionList.size(); i++) { requestActionList.get(i).perform(builder, objects[i]); } } return builder.setSecLevel(security).build().post(mReturnType); }//executebuilder.setSecLevel(security).build().post(mReturnType);

转载地址:http://olqpo.baihongyu.com/

你可能感兴趣的文章
Tomcat配置多数据源
查看>>
js string format
查看>>
httpHandlers和httpModules接口介绍 (3)
查看>>
《大话数据结构》第9章 排序 9.1 开场白
查看>>
Xgcalendar 新增Php demo
查看>>
poj2774
查看>>
xsi插件的安装方法
查看>>
查询指定库中所有表
查看>>
黄聪:用php判断当前用户访问网站是否为手机登录
查看>>
Flash AS3 Loader的一些总结
查看>>
.net(vs2010)调试技巧
查看>>
45个纯 CSS 实现的精美边框效果【附在线演示和源码】【下篇】
查看>>
js的逻辑 OR 运算符- ||
查看>>
[SQL Server]一次执行资料夹内的.sql 指令码
查看>>
【计算机视觉】粒子滤波跟踪
查看>>
hadoop集群扩展
查看>>
操作系统诊断
查看>>
[Compose] 19. Leapfrogging types with Traversable
查看>>
Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web modules
查看>>
2015年度新增开源软件排名TOP100
查看>>