Retrofit 2.9.0
1 Retrofit
1.1 retrofit介绍
A type-safe HTTP client for Android and Java. 一个安全类型的http请求的客户端。
底层网络请求是基于okhttp,retrofit对其进行了封装,提供了方便高效的网络访问框架
1.2 Retrofit 使用
1.2.1 简单使用
class RetrofitActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//初始化一个Retrofit对象
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
//创建出GitHubApiService对象
val service = retrofit.create(ApiService::class.java)
//返回一个 Call 对象
val repos = service.listRepos("octocat")
//调用 enqueue 方法在回调方法里处理结果
repos.enqueue(object : Callback<List<Repo>?> {
override fun onFailure(call: Call<List<Repo>?>, t: Throwable) {
t.printStackTrace()
}
override fun onResponse(call: Call<List<Repo>?>, response: Response<List<Repo>?>) {
"response.code() = ${
response.code()}".logE()
}
})
}
}
//自己定义的 API 请求接口
interface ApiService {
@GET("users/{user}/repos")
fun listRepos(@Path("user") user: String?): Call<List<Repo>>
}
1.2.2 封装使用
public class RetrofitHelper {
private Retrofit retrofit;
private static RetrofitHelper instance = null;
final static String ROOT_URL = "http://xxxxx/";
public RetrofitHelper() {
//解决handshake failed问题
ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
.tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
.allEnabledCipherSuites()
.build();//解决在Android5.0版本以下https无法访问
ConnectionSpec spec1 = new ConnectionSpec.Builder(ConnectionSpec.CLEARTEXT).build();//兼容http接口
OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
.connectTimeout(60, TimeUnit.SECONDS)//设置超时时间
.readTimeout(60,TimeUnit.SECONDS);
httpClient.connectionSpecs(Arrays.asList(spec,spec1));
retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.client(httpClient.build())
.addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
public static RetrofitHelper getInstance() {
if (instance == null){
instance = new RetrofitHelper();
}
return instance;
}
public RetrofitService getServer(){
return retrofit.create(RetrofitService.class);//创建service对象
}
}
public interface RetrofitService {
@Headers("Content-Type:application/json;charset=UTF-8")
@POST("GpsData/getHotMapDate")
Observable<List<HotMapInfo>> getHisHotMapDateData(@Body RequestBody requestbody);
//...
}
public class DataManager {
private static DataManager instance;
private RetrofitService retrofitService;
public DataManager(){
this.retrofitService = RetrofitHelper.getInstance().getServer();
}
public static DataManager getInstance(){
if(instance==null){
instance = new DataManager();
}
return instance;
}
public Observable<List<HotMapInfo>> getHisHotMapDateData(RequestBody requestbody){
return retrofitService.getHisHotMapDateData(requestbody);
}
}
使用:
DataManager.getInstance()
.getHisHotMapDateData(requestBody)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(pointFutureInfos -> {
//获取数据
}, throwable -> {
//获取异常
});
2 主要类
- Retrofit:总揽全局一个类,一些配置,需要通过内部 Builder 类构建,比如CallAdapter、Converter等
- ApiService:自定义API接口,通过 Retrofit 的 create 方法进行实例化
- Call:Retrofit 的 Call,是执行网络请求的是一个顶层接口,具体实现类实际是一个 OkHttpCall
- Callback:请求结果回调
2.1 Retrofit
Retrofit 主要属性:
//Retrofit.java
public final class Retrofit {
// 根据接口中的方法名,存储方法对应的 Service 对象。
//这里的方法指的就是代理接口对象(ApiService)中定义的方法,ServiceMethod就是接口方法对应的解析信息
private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();
// 网络请求器的工厂,用来生成网络请求器,默认使用的OkHttp,实为OkHttpClient
final okhttp3.Call.Factory callFactory;
// 请求的url地址等信息,包括scheme、username、password、host、port、path、query、fragment等信息
final HttpUrl baseUrl;
// 数据转换器的工厂的集合,存储数据转换器工厂,来生成数据转换器
final List<Converter.Factory> converterFactories;
final int defaultConverterFactoriesSize;
// 网络请求适配器工厂的集合,存放请求适配器工厂,来生成请求适配器
final List<CallAdapter.Factory> callAdapterFactories;
final int defaultCallAdapterFactoriesSize;
// 回调方法执行器,在 Android 上默认是封装了 handler 的 MainThreadExecutor,
// 默认作用是:切换线程(子线程 -> 主线程)
final @Nullable Executor callbackExecutor;
// 是否提前创建 ServiceMethod 缓存的开关,如果为true,则在调retrofit.create(MovieService.class);
// 的时候就会生成 ServiceMethod 并添加到缓存里面,如果为false,则在调用方法获取call的时候才会生成 ServiceMethod 并添加到缓存里面。
final boolean validateEagerly;
}
Retrofit 的主要属性如上,他们是由 Retrofit 的内部类 Builder 来生成的,在调用 Builder 的 build() 时,会创建 Retrofit 对象。
使用 new Retrofit.Builder() 创建一个Builder对象:
//Builder.java
public static final class Builder {
private @Nullable okhttp3.Call.Factory callFactory;
private @Nullable HttpUrl baseUrl;
//内置转换器工厂
private final List<Converter.Factory> converterFactories = new ArrayList<>();
private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
private @Nullable Executor callbackExecutor;
private boolean validateEagerly;
Builder(Retrofit retrofit) {
callFactory = retrofit.callFactory;
baseUrl = retrofit.baseUrl;
// Do not add the default BuiltIntConverters and platform-aware converters added by build().
for (int i = 1,
size =
retrofit.converterFactories.size()
- Platform.get().createDefaultConverterFactories().size();
i < size;
i++) {
converterFactories.add(retrofit.converterFactories.get(i));
}
// Do not add the default, platform-aware call adapters added by build().
for (int i = 0,
size =
retrofit.callAdapterFactories.size() - retrofit.defaultCallAdapterFactoriesSize;
i < size;
i++) {
callAdapterFactories.add(retrofit.callAdapterFactories.get(i));
}
callbackExecutor = retrofit.callbackExecutor;
validateEagerly = retrofit.validateEagerly;
}
public Retrofit build() {
if (baseUrl == null) {
throw new IllegalStateException("Base URL required.");
}
//获取平台信息
Platform platform = Platform.get();
// 设置网络请求工厂,如果没有设置,就使用OkHttpClient作为网络请求工厂
okhttp3.Call.Factory callFactory = this.callFactory;
if (callFactory == null) {
callFactory = new OkHttpClient();
}
// 设置回调方法执行器,如果没有指定,就使用Android 平台指定的执行器(也就是回调到主线程)
Executor callbackExecutor = this.callbackExecutor;
if (callbackExecutor == null) {
callbackExecutor = platform.defaultCallbackExecutor();
}
// 获取自定义设置的请求适配器工厂集合(这里是通过 addCallAdapterFactory 添加的),添加到 adapterFactories ,
// 然后再把 platform 设置的平台默认网络请求适配器工厂也加入 callAdapterFactories
List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
List<? extends CallAdapter.Factory> defaultCallAdapterFactories =
platform.createDefaultCallAdapterFactories(callbackExecutor);
callAdapterFactories.addAll(defaultCallAdapterFactories);
// 获取自定义设置的数据转换器工厂集合(这里是通过addConverterFactory 添加的),
// 添加到 converterFactories,注意此时在创建 Builder 的时候已经把内置的转换器工厂添加进去
List<? extends Converter.Factory> defaultConverterFactories =
platform.createDefaultConverterFactories();
int defaultConverterFactoriesSize = defaultConverterFactories.size();
List<Converter.Factory> converterFactories =
new ArrayList<>(1 + this.converterFactories.size() + defaultConverterFactoriesSize);
converterFactories.add(new BuiltInConverters());
converterFactories.addAll(this.converterFactories);
converterFactories.addAll(defaultConverterFactories);
// 调用Retrofit 的构造方法创建 Retrofit。需要注意的是 validateEagerly 默认是false的,
// 也就是不提前缓存ServiceMethod。
return new Retrofit(
callFactory,
baseUrl,
unmodifiableList(converterFactories),
defaultConverterFactoriesSize,
unmodifiableList(callAdapterFactories),
defaultCallAdapterFactories.size(),
callbackExecutor,
validateEagerly);
}
}
//Platform.java
abstract class Platform {
private static final Platform PLATFORM = createPlatform();
static Platform get() {
return PLATFORM;
}
private static Platform createPlatform() {
switch (System.getProperty("java.vm.name")) {
case "Dalvik":
if (Android24.isSupported()) {
return new Android24();
}
return new Android21();
case "RoboVM":
return new RoboVm();
default:
if (Java16.isSupported()) {
return new Java16();
}
if (Java14.isSupported()) {
return new Java14();
}
return new Java8();
}
}
}
这里返回的平台时 Android21 或者 Android24 (7.0以上)
//Platform.java
@IgnoreJRERequirement // Only used on Android API 24+
@TargetApi(24)
private static final class Android24 extends Platform {
static boolean isSupported() {
return Build.VERSION.SDK_INT >= 24;
}
private @Nullable Constructor<Lookup> lookupConstructor;
// 获取 Android 平台默认的callback 回调处理器,这里返回的是MainThreadExecutor
// MainThreadExecutor 是 Android 的一个静态内部类,里面初始化了 主线程的 Handler
// 也就是最后收到服务器响应以后切换到主线程处理消息。
@Override
Executor defaultCallbackExecutor() {
return MainThreadExecutor.INSTANCE;
}
// 获取默认的请求适配器工厂,这里使用的 DefaultCallAdapterFactory。用于在执行异步请求时候在适配器中生成的Executor 中执行。
// Retrofit 支持的六种请求适配器,分别为:DefaultCallAdapterFactory/(Rxjava1/2/3)/Guava/java8
@Override
List<? extends CallAdapter.Factory> createDefaultCallAdapterFactories(
@Nullable Executor callbackExecutor) {
return asList(
new CompletableFutureCallAdapterFactory(),
new DefaultCallAdapterFactory(callbackExecutor));
}
@Nullable
@Override
public Object invokeDefaultMethod(
Method method, Class<?> declaringClass, Object proxy, Object... args) throws Throwable {
if (