Retrofit的集成及使用

823 阅读1分钟

Retrofit的集成及使用

添加依赖:

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

使用:

第一步:创建api接口

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进行网络请求

 @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();
            }
        });
    }