序言
本来想县写一篇关于Retrofit使用的文章为开端,不过网上到处都是而且也比较简单,写了也没人看哈。于是就从基本封装开始吧。
基本使用可以看这里Retrofit官方文档
目的
下面这个是Retrofit基本用法,可以发现每次调用请求的时候都需要创建一次retrofit对象,我们的目的就是简化请求操作,不用多次配置Retrofit。
private void requestA() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.186:9042/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService service = retrofit.create(ApiService.class);
Call<UserInfoEntity> user = service.login("username", "pwd");
user.enqueue(new Callback<UserInfoEntity>() {
@Override
public void onResponse(Call<UserInfoEntity> call, Response<UserInfoEntity> response) {
Toast.makeText(MainActivity.this, response.body().getRealName(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(Call<UserInfoEntity> call, Throwable t) {
}
});
}
环境配置
dependencies {
//retrofit 2.1.0
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//gson转换工厂
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
//log拦截器
compile 'com.squareup.okhttp3:logging-interceptor:3.1.2'
}
ApiService
在这里写网络请求接口
public interface ApiService {
@GET("stuLogin")
Call<UserInfoEntity> login(@Query("loginName") String user, @Query("password") String password);
}
ApiFactory
该类单例操作,在这个封装类里面操作的内容
1. 构建okhttpclient
(1) 设置log拦截器
(2) 设置网络缓存拦截器
(3) 设置超时时间
2. 构建Retrofit
(1)设置网络客户端okhttpclient
(2)设置转换方式GsonConverterFactory
(3)设置基础URL
(4)还可以设置addCallAdapterFactory,在这里可以配置rxJava
/**
* Created by HJ on 2016-09-09.
* api封装类
*/
public class ApiFactory {
private static ApiFactory ourInstance = new ApiFactory();
public static ApiFactory getInstance() {
return ourInstance;
}
public Retrofit retrofit;
public ApiService apiService;
private ApiFactory() {
//网络请求信息拦截器设置
HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//设置缓存路径缓存大小
File cacheFile = new File(MyApplication.getContext().getCacheDir(), "cache");
Cache cache = new Cache(cacheFile, 1024 * 1024 * 100); //100Mb
//okhttp客户端构建
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(10000, TimeUnit.MILLISECONDS)
.connectTimeout(10000, TimeUnit.MILLISECONDS)
.addInterceptor(logInterceptor)
.addNetworkInterceptor(new HttpCacheInterceptor())
.build();
//retrofit构建
retrofit = new Retrofit.Builder()
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(RequestLinks.COMMON_HEAD)
.build();
apiService = retrofit.create(ApiService.class);
}
/**
* 网络缓存拦截器
*/
class HttpCacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetWorkUtil.isNetConnected(MyApplication.getContext())) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
Log.d("Okhttp", "no network");
}
Response originalResponse = chain.proceed(request);
if (NetWorkUtil.isNetConnected(MyApplication.getContext())) {
String cacheControl = request.cacheControl().toString();
return originalResponse.newBuilder()
.header("Cache-Control", cacheControl)
.removeHeader("Pragma")
.build();
} else {
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=2419200")
.removeHeader("Pragma")
.build();
}
}
}
}
请求调用
private void request() {
Call<UserInfoEntity> user = ApiFactory.getInstance().apiService.login("username", "pwd");
user.enqueue(new Callback<UserInfoEntity>() {
@Override
public void onResponse(Call<UserInfoEntity> call, Response<UserInfoEntity> response) {
Log.d("request", response.body().getRealName());
}
@Override
public void onFailure(Call<UserInfoEntity> call, Throwable t) {
}
});
}