本文共 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);
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的主要技术细节包括:
1.接口的实例化 2.获取泛型的返回值type(数据的解析和实例化观察者需要) 3.获取Method之后通过反射获取方法注解和参数注解我们忽略了一些AOP编程的细节,而是主要去关注一个注解方法对象(Method)的解析过程。
retrofit将Method对象解析成对应http request;将request的参数给下层的网络适配器adapter(可以认为是OkhttpAdapter),适配器调用自身execute方法,调用成功后通过线程分发器发送到对应的线程。至此,完成了retrofit对网络的完整的抽象。publicT 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); } }
主要实现的步骤:
//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 ListrequestActionList = new ArrayList<>();
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/