简单的实例
public interface MyInterface {
@GET(".../...")
Call<List<MyResponse>> getCall();
}
public class RetrofitS {
public void MyRetrofit() throws IOException {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://xxx.xxx.com/") // 设置网络请求的Url地址
.addConverterFactory(GsonConverterFactory.create()) // 设置数据解析器
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平台
.build();
MyInterface myInterface = retrofit.create(MyInterface.class);
Call call = myInterface.getCall();
//retrofit同步请求
call.execute();
call.enqueue(new retrofit2.Callback() {
@Override
public void onResponse(Call call, retrofit2.Response response) {
System.out.println(response.body());
}
@Override
public void onFailure(Call call, Throwable throwable) {
System.out.println("请求失败");
}
});
}
}
@GET 完整URL = baseURL + get请求的路径
{}表示动态参数中获取
@Path("user") 表示参数为空的默认值
addConverterFactory用来映射我们response对象的解析器
service.listRepos 返回Call是OkHttp中的,在调用它的异步接口
代理
静态代理
动态代理
jdk动态代理
public interface Subject{
void shopping();
}
public class Proxy implements InvocationHandler {
private Object target;//要代理的真实对象
public Proxy(Subject target){
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("proxy:"+proxy.getClass().getName());
System.out.println("before...");
method.invoke(target, args);
System.out.println("after...");
return null;
}
}
public class Client {
public static void main(String[] args) {
Subject man = new Man();
Proxy p = new Proxy(man);
//通过java.lang.reflect.newProxyInstance(...)方法获得真实对象的代理对象
Subject subject = (Subject)java.lang.reflect.Proxy.
newProxyInstance(man.getClass().getClassLoader(),
man.getClass().getInterfaces(), p);
//通过代理对象调用真实对象相关接口中实现的方法,这个时候就会跳转到这个代理对象所关联的handler的invoke()方法去执行
subject.shopping();
//获得真实对象的代理对象所对应的Class对象的名称,用字符串表示
System.out.println(subject.getClass().getName());
}
}
CGLIB
Retrofit8个步骤
- build初始化,Platform.get()反射获得安卓平台
public static final class Builder {
private Platform platform;
private okhttp3.Call.Factory callFactory;
private HttpUrl baseUrl;
private List<Converter.Factory> converterFactories = new ArrayList<>();
private List<CallAdapter.Factory> adapterFactories = new ArrayList<>();
private Executor callbackExecutor;
private boolean validateEagerly;
Builder(Platform platform) {
this.platform = platform;
// Add the built-in converter factory first. This prevents overriding its behavior but also
// ensures correct behavior when using converters that consume all types.
converterFactories.add(new BuiltInConverters());
}
public Builder() {
this(Platform.get());
}
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// Make a defensive copy of the adapters and add the default Call adapter.
List<CallAdapter.Factory> adapterFactories = new ArrayList<>(this.adapterFactories);
adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
// Make a defensive copy of the converters.
List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
callbackExecutor, validateEagerly);
}
static class Android extends Platform {
@Override public Executor defaultCallbackExecutor() {
return new MainThreadExecutor();
}
@Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
return new ExecutorCallAdapterFactory(callbackExecutor);
}
static class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override public void execute(Runnable r) {
handler.post(r);
}
}
}
总结:
Retrofit通过构建模式初始化callFactory,baseUrl,converterFactories,adapterFactories, callbackExecutor, validateEagerly
这些参数的基本信息
callFactory——OkHttpClient
converterFactories——解析器
adapterFactories——平台适配器
callbackExecutor——子线程和主线程切换(handler)
validateEagerly——response是否立即解析
MyInterface myInterface = retrofit.create(MyInterface.class);
create里面通过动态代理生成一个代理对象,通过ServiceMethod拿到注解信息,创建OkHttpCall对象,通过传入ServiceMethod和args
private okhttp3.Call createRawCall() throws IOException {
Request request = serviceMethod.toRequest(args);
okhttp3.Call call = serviceMethod.callFactory.newCall(request);
if (call == null) {
throw new NullPointerException("Call.Factory returned null.");
}
return call;
}
在代理类的invoke方法中serviceMethod.callAdapter.adapt(okHttpCall);
默认返回的ExecutorCallbackCall
指定RxJavaCallAdapterFactory返回一个observable,通知方法中requestArbiter请求
CallOnSubscribe(Call<T> originalCall) {
this.originalCall = originalCall;
}
@Override public void call(final Subscriber<? super Response<T>> subscriber) {
// Since Call is a one-shot type, clone it for each new subscriber.
Call<T> call = originalCall.clone();
// Wrap the call in a helper which handles both unsubscription and backpressure.
RequestArbiter<T> requestArbiter = new RequestArbiter<>(call, subscriber);
subscriber.add(requestArbiter);
subscriber.setProducer(requestArbiter);
}
}
//请求
public void setProducer(Producer p) {
...
producer.request(Long.MAX_VALUE);
...
}
@Override public void request(long n) {
...
Response<T> response = call.execute();
...
}