Android中中Retrofit+OkHttp进行进行HTTP网络编程的使用指南网络编程的使用指南
Retrofit和OkHttp都是Square在GitHub上开源的第三方HTTP支持包,两个包可以搭配使用,本文即是来讲解
Android中Retrofit+OkHttp进行HTTP网络编程的使用指南:
Retrofit介绍:介绍:
Retrofit(GitHub主页https://github.com/square/okhttp)和OkHttp师出同门,也是Square的开源库,它是一个类型安全的网络
请求库,Retrofit简化了网络请求流程,基于OkHtttp做了封装,解耦的更彻底:比方说通过注解来配置请求参数,通过工厂来生
成CallAdapter,Converter,你可以使用不同的请求适配器(CallAdapter), 比方说RxJava,Java8, Guava。你可以使用不同的
反序列化工具(Converter),比方说json, protobuff, xml, moshi等等。
官网 http://square.github.io/retrofit/
github https://github.com/square/retrofit
Retrofit使用:使用:
1.在在build.gradle中添加如下配置中添加如下配置
compile 'com.squareup.retrofit2:retrofit:2.0.2'
2.初始化初始化Retrofit
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(FastJsonConverterFactory.create())
.client(mOkHttpClient)
.build();
3.初始化初始化OkHttpClient
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
.connectTimeout(10, TimeUnit.SECONDS)//设置超时时间
.readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(10, TimeUnit.SECONDS);//设置写入超时时间
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(App.getContext().getCacheDir(), cacheSize);
builder.cache(cache);
builder.addInterceptor(interceptor);
mOkHttpClient = builder.build();
关于okHttp的拦截器、Cache-Control等这里就不再做解说了
4.关于关于ConverterFactory
对于okHttpClient的初始化我们都已经很熟悉了,对ConverterFactory初次接触多少有点陌生,其实这个就是用来统一解析
ResponseBody返回数据的。
常见的ConverterFactory
Gson: com.squareup.retrofit2:converter-gson
Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
由于项目中使用的是FastJson,所以只能自己自定义ConverterFactory。
5.定义接口定义接口 get 请求请求
(1)get请求 不带任何参数
public interface IApi {
@GET("users")//不带参数get请求
Call<List<User>> getUsers();
}
(2)get请求 动态路径 @Path使用
public interface IApi {
@GET("users/{groupId}")//动态路径get请求
Call<List<User>> getUsers(@Path("userId") String userId);
}
评论0
最新资源