Retrofit的集成及使用json
添加依賴:api
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
複製代碼
使用:緩存
第一步:建立api接口markdown
public interface Api {
@GET("hot")
Call<List<String>> listHot();
@GET("recommend")
Call<List<String>> listRecommend();
@GET("category")
Call<List<CategoryItemBean>> listCategory();
@GET("subject")
Call<List<SubjectItemBean>> listSubject(@Query("index") int index);
@GET("game")
Call<List<AppListItemBean>> listGame(@Query("index") int index);
@GET("app")
Call<List<AppListItemBean>> listApp(@Query("index") int index);
@GET("home")
Call<HomeBean> listHome(@Query("index") int index);
@GET("detail")
Call<AppDetailBean> getAppDetail(@Query("packageName") String packageName);
}
複製代碼
第二步:封裝Retrofit對象網絡
public class HeiMaRetrofit {
private static HeiMaRetrofit sHeiMaRetrofit;
private Api mApi;
private Gson mGson = new GsonBuilder().setLenient().create();//設置寬大處理畸形的json
private static final int CACHE_MAX_SIZE = 5 * 1024 * 1024;
private HeiMaRetrofit() {
}
public void init(Context context) {
//緩存的路徑
String cacheDir = context.getCacheDir().getAbsolutePath() + "/response";
File file = new File(cacheDir);
if (!file.exists()) {
file.mkdirs();//建立緩存目錄
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cache(new Cache(file, CACHE_MAX_SIZE))
.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(mGson))//添加轉換器
.build();
mApi = retrofit.create(Api.class);
}
public static HeiMaRetrofit getInstance() {
if (sHeiMaRetrofit == null) {
synchronized (HeiMaRetrofit.class) {
if (sHeiMaRetrofit == null) {
sHeiMaRetrofit = new HeiMaRetrofit();
}
}
}
return sHeiMaRetrofit;
}
public Api getApi() {
return mApi;
}
//在okhttp在回調網絡以前咱們能夠攔截這個響應,作處理在返回回去
private static Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
CacheControl control = new CacheControl.Builder().maxAge(5, TimeUnit.MINUTES).build();
Response responseAfterModify = response.newBuilder().header("Cache-Control", control.toString()).build();
return responseAfterModify;
}
};
}
複製代碼
第三步:使用Retrofit進行網絡請求app
@Override
protected void startLoadData() {
Api api = HeiMaRetrofit.getInstance().getApi();//獲取API接口
Call<List<String>> listCall = api.listHot();//獲取Call
// listCall.execute();//同步網絡請求
listCall.enqueue(new Callback<List<String>>() {
//主線程執行
@Override
public void onResponse(Call<List<String>> call, Response<List<String>> response) {
mDataList = response.body();
onDataLoadSuccess();
}
@Override
public void onFailure(Call<List<String>> call, Throwable t) {
onDataLoadFailed();
}
});
}
複製代碼