Retrofit的简单封装--更方便的配置okhttp

前言:

Retrofit作为简化HTTP请求的库,已经运行多年,2.0版本依然不辱使命的在做这些事情。不过2.0版本修复了一些长期影响开发者的设计,还加入了前所未有的强大特性。在NYC2015的这一个分享中,Jake Wharton的演讲涵盖了所有Retrofit2.0的新特性,全面介绍了Retrofit2.0工作原理。看我

首先给出官网源码(点我)和基础使用方法(点我

初始配置就看官网了,废话不多说,开始封装:

一、Api请求网络配置

(1)添加所需要的配置:

public class NetConfig {
    File RESPONSE_CACHE;//缓存文件
    int RESPONSE_CACHE_SIZE;//缓存文件大小
    int CONNET_TIMEOUT;//连接超时
    int READ_TIMEOUT;//读取新链接超时
    int MAX_CACHE_AGE;//从文档被访问后的存活时间
    Context context;

    public NetConfig(File RESPONSE_CACHE,int RESPONSE_CACHE_SIZE,int CONNET_TIMEOUT,int READ_TIMEOUT,int MAX_CACHE_AGE,Context context){
        this.RESPONSE_CACHE = RESPONSE_CACHE;
        this.RESPONSE_CACHE_SIZE = RESPONSE_CACHE_SIZE;
        this.CONNET_TIMEOUT = CONNET_TIMEOUT;
        this.READ_TIMEOUT = READ_TIMEOUT;
        this.MAX_CACHE_AGE = MAX_CACHE_AGE;
        this.context = context;
    }
}

(2)通过构建者模式设置默认初始网络配置

public class NetConfigBuilder {

    private File response_cache;
    private int response_cache_size = 5 * 1024 * 1024;
    private int connect_timeout = 8 * 1000;
    private int read_timeout = 5 * 1000;
    private Context appContext;
    private int maxCacheAge = 0;

    /**
     * request cache-control
     */
    public NetConfigBuilder maxCacheAge(int maxCacheAge) {
        this.maxCacheAge = maxCacheAge;
        return this;
    }

    /**
     * local cache dir
     */
    public NetConfigBuilder responseCacheDir(File response_cache) {
        this.response_cache = response_cache;
        return this;
    }

    /**
     * local cache size
     */
    public NetConfigBuilder responseCacheSize(int response_cache_size) {
        this.response_cache_size = response_cache_size;
        return this;
    }

    /**
     * readTime
     *
     * @param connect_timeout millisecond
     */
    public NetConfigBuilder connectionTimeout(int connect_timeout) {
        this.connect_timeout = connect_timeout;
        return this;
    }

    /**
     * timeout
     *
     * @param read_timeout millisecond
     */
    public NetConfigBuilder readTimeout(int read_timeout) {
        this.read_timeout = read_timeout;
        return this;
    }

    /**
     * must set Context
     */
    public NetConfigBuilder context(Context app) {
        this.appContext = app.getApplicationContext();
        return this;
    }

    public NetConfig createNetConfig() {
        return new NetConfig(response_cache, response_cache_size, connect_timeout, read_timeout, maxCacheAge, appContext);
    }
}

(3)在全局Application中初始化自己配置:

public abstract class NetUtils {
    public static NetConfig netConfig;

    public static void setNetConfig(NetConfig netConfig){
        NetUtils.netConfig = netConfig;
    }

    public static <T> T createApi(Class<T> clazz, String host){
        if(netConfig.context == null)
            throw new IllegalArgumentException("must be set Context,use NetUtils.setNetConfig() at once");
        return RetrofitUtils.createApi(netConfig.context,clazz,host);
    }
}
public class App extends Application{
    private static Context context;

    //获取全局context
    public static Context getContext(){
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

        /**
         * net config
         */
        final NetConfig netConfig = new NetConfigBuilder()
                .context(this)
                .responseCacheDir(new File(context.getCacheDir(),"mycache"))
                .responseCacheSize(1024 * 1024 * 100)
                .readTimeout(2000)
                .createNetConfig();
        NetUtils.setNetConfig(netConfig);
    }
}

二、配置Retrofit和OkHttp

(1)OkHttpUtils可通过设置拦截器等okhttp的初始配置:

public class OkHttpUtils {

    private final static File RESPONSE_CACHE = NetUtils.netConfig.RESPONSE_CACHE;
    private final static int RESPONSE_CACHE_SIZE = NetUtils.netConfig.RESPONSE_CACHE_SIZE;
    private final static int CONNECT_TIMEOUT = NetUtils.netConfig.CONNET_TIMEOUT;
    private final static int READ_TIMEOUT = NetUtils.netConfig.READ_TIMEOUT;
    private static OkHttpClient singleton;

    static OkHttpClient getSingleton(final Context context){
        if(singleton == null){
            synchronized (OkHttpUtils.class){
                if(singleton == null){
                    singleton = new OkHttpClient().newBuilder()
                            .cache(new Cache(RESPONSE_CACHE != null?RESPONSE_CACHE:new File(context.getCacheDir(),"defalut_cache"),RESPONSE_CACHE_SIZE))
                            .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.MILLISECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                            .build();
                }
            }
        }
        return singleton;
    }

    private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Response originalResponse = chain.proceed(chain.request());
            if (NetUtil.isNetworkAvailable(App.getContext())) {
                int maxAge = 60; // 在线缓存在1分钟内可读取
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();
            } else {
                int maxStale = 60 * 60 * 24 * 28; // 离线时缓存保存4周
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                        .build();
            }
        }
    };
}

(2)RetrofitUtilsze则初始化Retrofit2配置:

public class RetrofitUtils {

    private static Retrofit singleton;

    static <T> T createApi(Context context, Class<T> clazz, String host){
        if(singleton == null){
            synchronized (RetrofitUtils.class){
                if(singleton == null){
                    singleton = new Retrofit.Builder()
                            .baseUrl(host)
                            .addConverterFactory(GsonConverterFactory.create())
                            .client(OkHttpUtils.getSingleton(context))
                            .build();
                }
            }
        }


        return singleton.create(clazz);
    }

}

三、使用

(1)定义接口,封装访问的方法:

public interface AllApi {

    @GET("txapi/mvtp/meinv")
    Call<GrilBean> getGril(@Header("apikey") String key, @Query("num") int num);

}

(2)调用访问的方法:

public class ApiUser {
    public static AllApi get(){
        return NetUtils.createApi(AllApi.class, Constant.url);
    }
}

Call<GrilBean> call = ApiUser.get().getGril(Constant.AES_KEY,12);
call.enqueue(new Callback<GrilBean>() {
    @Override
    public void onResponse(Call<GrilBean> call, Response<GrilBean> response) {
        if (response.isSuccessful()) {
            GrilBean result = response.body();
            //具体操作......
        }
    }

    @Override
    public void onFailure(Call<GrilBean> call, Throwable t) {

    }
});

四、总结

上面只是给出个初始的封装,后续可根据其添加所需配置,源码请看这里

总之,Retrofit解耦的很彻底:比方说通过注解来配置请求参数,通过工厂来生成CallAdapter,Converter,你可以使用不同的请求适配器(CallAdapter),比方说RxJava,Java8,Guava。你可以使用不同的反序列化工具(Converter),比方说son,protobuff,xml,moshi等等。所以非常推荐使用。







  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值