一、Retrofit是什么?
准确来说,Retrofit是一个对http网络请求框架的封装,因为网络请求的本质上是OkHttp完成的,而Retrofit仅仅负责网络请求接口的封装。
Retrofit的使用:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("www.xxx.com")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
StudentInter inter = retrofit.create(StudentInter.class);
Call<Student> studentCall = inter.studentInfo();
studentCall.enqueue(new Callback<Student>() {
@Override
public void onResponse(Call<Student> call, Response<Student> response) {
}
@Override
public void onFailure(Call<Student> call, Throwable t) {
}
});
1)build方法:就是个Retrofit设置各种参数。采用build设计模式
2)StudentInter inter = retrofit.create(StudentInter.class);
我们知道,StudentInter就是一个接口,想要给接口赋值,按照Java的语法,必须要是一个接口的实现类
retrofit.create(StudentInter.class):
内部有一个动态代理类Proxy。
3)使用Retrofit进行网络请求是时候,我们并没有感觉到是在调用OkHttp,这是Retrofit都已经帮我们封装好了,这采用的就是外观设计模式、门面设计模式。
总结:
Retrofit的核心思想就是动态代理+注解+反射以及包含各种设计模式