Retrofit配置

来源:互联网 发布:小众软件下载免费 编辑:程序博客网 时间:2024/06/06 03:53

之前写Lambda表达式运用的时候,提到了Retrofit框架,基于OkHttp的解决Android手机端访问服务端的数据接口的框架。使用中感到方便的地方是他能用注解完成接口定义,配合SwaggerUI,开发就像写文档一样,只不过接口返回值是基于Subscriber的理念,如果你的服务端接口返回了空值或者不在Retrofit定义范围内的返回值,那你需要自己定义适配器去处理。今天先简单说说它的配置和实现。

Gradle引入:

compile 'io.reactivex:rxandroid:1.2.1'compile 'com.squareup.retrofit2:retrofit:2.1.0'compile 'com.squareup.retrofit2:converter-gson:2.1.0'compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

初始化ApiService对象:

private ApiService(String baseUrl){        //缓存        File httpCacheDirectory=new File(BaseApplication.mContext.getCacheDir(),"responses");        int cacheSize=10*1024*1024;//10 MB        Cache cache=new Cache(httpCacheDirectory,cacheSize);        //设置应用拦截器,可用于设置公共参数,头信息,日志拦截等        HttpLoggingInterceptor logging=new HttpLoggingInterceptor();        logging.setLevel(HttpLoggingInterceptor.Level.BODY);        OkHttpClient client=new OkHttpClient.Builder()                .connectTimeout(30, TimeUnit.SECONDS)                .readTimeout(30,TimeUnit.SECONDS)                .addInterceptor(logging)                .retryOnConnectionFailure(true) //错误重联                .addInterceptor(new RewriteCacheControlInterceptor())                .cache(cache)                .build();        retrofit = new Retrofit.Builder()                .baseUrl(baseUrl)                .client(client)                .addConverterFactory(GsonConverterFactory.create())                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .build();    }

其实就是相当于打开连接的一些初始化参数设置。

你的接口方法可以通过下面设置进来:

/**     * 得到具体的Service     * @param service     * @param <T>     * @return     */    public <T> T create(Class<T> service){        return retrofit.create(service);    }

处理返回值:

public <T> void Subscribe(Observable<ApiResult<T>> observable, final IApiReturn<T> apiReturn){        observable.subscribeOn(Schedulers.io())                .observeOn(AndroidSchedulers.mainThread())                .subscribe(new Observer<ApiResult<T>>() {                    @Override                    public void onCompleted() {                        DialogUtil.dismissProgress();                    }                    @Override                    public void onError(Throwable e) {                        LogMe.e(e.getMessage(),e);                    }                    @Override                    public void onNext(ApiResult<T> apiResult) {                        apiReturn.run(apiResult);                    }                });    }

如何调用参考我的Lambda表达式运用的博文。

你具体的Api接口:

public interface ApiUserService  {    @GET("tokens/{phone}/code")    Observable<ApiResult<String>> getCode(@Path("phone")String phone);}

调用你的Api接口:

getApi().Subscribe(getApi().getUserService().getCode("13821990273"), new IApiReturn<String>() {            @Override            public void run(ApiResult<String> apiResult) {            }        });

OK,很简单的过了一遍使用Retrofit框架需要做的事情,我会在后面的博文中具体剖析这个框架,先到这里,希望大家指正。

0 0
原创粉丝点击