Retrofit源码的示例分析
这篇文章主要介绍了Retrofit源码的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:空间域名、网站空间、营销软件、网站建设、华坪网站维护、网站推广。
基本使用介绍
介绍源码前,我们先看下Retrofit的基本使用,大致了解下流程,跟着这个流程来分析源码才不会乱。
1、初始化Retrofit对象
Retrofit retrofit = new Retrofit.Builder() //使用自定义的mGsonConverterFactory .addConverterFactory(GsonConverterFactory.create()) .baseUrl("http://apis.baidu.com/txapi/") .build();
2、定义接口
public interface APi { @GET("hello/world") CallgetNews(@Query("num") String num,@Query("page")String page); }
3、发起网络请求
mApi = retrofit.create(APi.class); Callnews = mApi.getNews("1", "10"); news.enqueue(new Callback () { @Override public void onResponse(Call call, Response response) { } @Override public void onFailure(Call call, Throwable t) { } });
Retrofit本质分析
看到上面的整个流程,不去探究源码的话肯定一脸懵逼,我就定义了一个接口,指定了下返回值,为毛这个接口就可以直接用了?接口的实现呢?我随便写一个返回值,不指定返回Call行不行?待着这些疑问,我们大致也可以猜出Retrofit是干什么的了。
猜测:Retrofit主要就是为我们定义的接口创造了一个实例,然后这个实例调用接口中的方法将我们定义在注解中的值拼装成发起http请求所要的信息,最后利用这些信息产生一个我们在接口返回值中规定的对象,这个对象可以用来发起真正的请求。
简单的讲,Retrofit就是把注解中的东西拼成http请求的对象,然后由这个对象去发起请求。
验证猜测
是谁实现了这个接口
发起网络请求时,有这样一句:
mApi = retrofit.create(APi.class);
很明显,接口的实现应该是这个create干的事,我们跟进去看看源码:
publicT create(final Class 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(); @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); } ServiceMethod