十分钟教你手撸一个简单的Retrofit demo
众所周知,retrofit框架是square公司旗下的著名的http请求框架,今天我们来理一理它的主要逻辑,并写一个demo,这里涉及到java中注解,反射,泛型等知识点和构建者模式、动态代理,和我一起来一探究竟吧。
Retrofit的具体用法请自行百度,下面是关键的三行代码
//利用构建者模式实例化Retrofit Retrofit retrofit = new Retrofit.Builder().baseUrl("https://restapi.amap.com/").build(); //通过动态代理生成接口的实例对象,并实现接口中定义的方法; apiService = (ApiService) retrofit.create(ApiService.class); //代理对象去做http请求 Call call = (Call) apiService.get("110101","ae6c53e2186f33bbf240a12d80672d1b");
先想一想做http请求,我们需要什么?需要域名,请求方式,请求参数,嗯,还需要Okhttp
实现Retrofit第一步
构建MyRetrofit类,在里边儿定义一个内部Builder类,构建者模式是将一个复杂的对象一步一步建立起来。然后在Builder类型中baseUrl方法准备好域名,callFactory准备好OKHttp ,build()方法将获得的参数传入MyRetrofit构造方法,返回MyRetrofit实例对象。
public class MyRetrofit {
public final HttpUrl baseUrl;
public final Call.Factory factory;
public MyRetrofit(HttpUrl baseUrl, Call.Factory factory){
this.baseUrl = baseUrl;
this.factory = factory;
}
public static final class Builder{
private HttpUrl baseUrl;
private Call.Factory factory;
public Builder baseUrl(String url){
if(url != null){
baseUrl = HttpUrl.get(url);
}
return this;
}
public Builder callFactory(Call.Factory factory){
if(factory != null){
this.factory = factory;
}
return this;
}
public MyRetrofit build(){
if(this.factory == null){
this.factory = new OkHttpClient();
}
return new MyRetrofit(baseUrl,factory);
}
}
}
实现Retrofit第二步
通过接口创建代理对象, 并在invoke的回调中实现apiService中定义的方法。代理模式是类似于中介代理的某项服务,类似于租房,你不需要知道房东是谁,只需要找中介就能租,静态代理是租房找租房中介,留学找留学中介,相亲找媒婆;而动态代理就很牛了,不管是租房,留学还是相亲都可以找这个中介,即静态代理是一个