Retrofit2.0在android项目中的使用

Retrofit2.0github官方文档 

 

 Retrofit2.0简介:

 

Retrofit2.0是Square公司出品的针对于Android和Java的类型安全的Http客户端,网络请求是基于OkHttp.

 

Retrofit2.0的改进

 

Retrofit2.0的使用:

 

下载jar包

 

Gradle:配置:

 

compile 'com.squareup.retrofit2:retrofit:2.1.0'
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'io.reactivex:rxjava:1.1.0'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
    compile 'com.google.code.gson:gson:2.6.2'
    compile 'com.jakewharton:butterknife:7.0.1'
}

用法介绍:

 

创建接口 NetworkService.java

 

Public Interface NetworkService{
/**
     *   获取码表数据
     * @param info
     * @return
     */
    @POST("getCodeList")
    Call getCodeList(@Body EncryptUpload info) ;
}

创建ApiService.java

 

 

public class ApiService {

    private  Retrofit retrofit ;
    private static NetworkService networkService ;

    private static ApiService ourInstance ;



    public static ApiService getInstance() {
        if (ourInstance==null) {
            ourInstance = new ApiService();
        }
        return ourInstance;
    }

    private ApiService() {
        retrofit=  RetrofitManager.builder();
        networkService= retrofit.create(NetworkService.class);
    }

    /***
     * 获取码表数据
     */
    public  void getCodeList(JSONObject json,  Callback callback){
        EncryptUpload encryptUpload = toEncry(json,"getCodeList");
        Call  call =  networkService.getCodeList(encryptUpload);

        call.enqueue(callback);
    }
}

在外部调用:

 

 

private  void getCodeList(){
        if (AppConfig.IS_OFFLINE) return;

        JSONObject jsonObject = new JSONObject();
        String  lastUpdateTime =   PreferenceUtil.getStringData(this, AppConfig.PRE_CODE_LATEST_UPDATED_TIME);
        try {
            jsonObject.put("lastUpdateTime",lastUpdateTime);

            ApiService.getInstance().getCodeList(jsonObject, new Callback() {

                @Override
                public void onResponse(Call call, Response response) {

                    if (!response.isSuccessful()){
                        ToastUtil.show(getBaseContext(),"请求异常");
                        return;
                    }

                    if(AppConfig.handleResponse(MainActivity.this,(BaseResponse)response.body())){

                        List  addList    =response.body().getAddList();
                        List  updateList    =response.body().getUpdateList();
                        List  deleteList    =response.body().getDeleteList();


                        try {

                            //模板 更新
                            if (addList!=null&&addList.size()>0)
                                CreditApplication.getDbManager().saveOrUpdate(addList);
                            if (updateList!=null&&updateList.size()>0)
                                CreditApplication.getDbManager().saveOrUpdate(updateList);
                            if (deleteList!=null&&deleteList.size()>0)
                                CreditApplication.getDbManager().deleteById(CodeList.class,deleteList);
                            //时间 更新
                            PreferenceUtil.setStringData(getBaseContext(), AppConfig.PRE_CODE_LATEST_UPDATED_TIME,response.body().getLastUpdateTime());
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }

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

                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    } JSONObject jsonObject = new JSONObject();
        String  lastUpdateTime =   PreferenceUtil.getStringData(this, AppConfig.PRE_CODE_LATEST_UPDATED_TIME);
        try {
            jsonObject.put("lastUpdateTime",lastUpdateTime);

            ApiService.getInstance().getCodeList(jsonObject, new Callback() {

                @Override
                public void onResponse(Call call, Response response) {

                    if (!response.isSuccessful()){
                        ToastUtil.show(getBaseContext(),"请求异常");
                        return;
                    }

                    if(AppConfig.handleResponse(MainActivity.this,(BaseResponse)response.body())){

                        List  addList    =response.body().getAddList();
                        List  updateList    =response.body().getUpdateList();
                        List  deleteList    =response.body().getDeleteList();


                        try {

                            //模板 更新
                            if (addList!=null&&addList.size()>0)
                                CreditApplication.getDbManager().saveOrUpdate(addList);
                            if (updateList!=null&&updateList.size()>0)
                                CreditApplication.getDbManager().saveOrUpdate(updateList);
                            if (deleteList!=null&&deleteList.size()>0)
                                CreditApplication.getDbManager().deleteById(CodeList.class,deleteList);
                            //时间 更新
                            PreferenceUtil.setStringData(getBaseContext(), AppConfig.PRE_CODE_LATEST_UPDATED_TIME,response.body().getLastUpdateTime());
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    }
                }

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

                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

 

RetrofitManager.java

 

 

import com.psbc.credit.AppConfig;
import com.psbc.credit.CreditApplication;
import com.psbc.credit.util.NetworkUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by rance on 2016/11/10.
 */

public class RetrofitManager {


    //短缓存有效期为1分钟
    public static final int CACHE_STALE_SHORT = 60;
    //长缓存有效期为7天
    public static final int CACHE_STALE_LONG = 60 * 60 * 24 * 7;

    public static final String CACHE_CONTROL_AGE = "Cache-Control: public, max-age=";

    //查询缓存的Cache-Control设置,为if-only-cache时只查询缓存而不会请求服务器,max-stale可以配合设置缓存失效时间
    public static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_LONG;
    //查询网络的Cache-Control设置,头部Cache-Control设为max-age=0时则不会使用缓存而请求服务器
    public static final String CACHE_CONTROL_NETWORK = "max-age=0";
    private static OkHttpClient mOkHttpClient;
    private static Retrofit retrofit;
    public static Retrofit builder(){
        return new RetrofitManager().retrofit;
    }

    private RetrofitManager() {

        initOkHttpClient();

         retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.HOST_URL)
                .client(mOkHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private void initOkHttpClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (mOkHttpClient == null) {
            synchronized (RetrofitManager.class) {
                if (mOkHttpClient == null) {

                    // 指定缓存路径,缓存大小100Mb
                    Cache cache = new Cache(new File(CreditApplication.getContext().getCacheDir(), "HttpCache"),
                            1024 * 1024 * 100);

                    mOkHttpClient = new OkHttpClient.Builder()
                            .cache(cache)
                            .addInterceptor(mRewriteCacheControlInterceptor)
                            .addNetworkInterceptor(mRewriteCacheControlInterceptor)
                            .addInterceptor(interceptor)
                            .retryOnConnectionFailure(true)
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .readTimeout(60,TimeUnit.SECONDS)
                            .writeTimeout(60,TimeUnit.SECONDS)
                            .build();
                }
            }
        }
    }

    // 云端响应头拦截器,用来配置缓存策略
    private Interceptor mRewriteCacheControlInterceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtil.isNetworkConnected()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }

            okhttp3.Response originalResponse =  chain.proceed(request);
            if (NetworkUtil.isNetworkConnected()) {
                //有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
                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=" + CACHE_STALE_LONG)
                        .removeHeader("Pragma").build();
            }
        }
    };

}
  retrofit = new Retrofit.Builder()
                .baseUrl(AppConfig.HOST_URL)
                .client(mOkHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    private void initOkHttpClient() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        if (mOkHttpClient == null) {
            synchronized (RetrofitManager.class) {
                if (mOkHttpClient == null) {

                    // 指定缓存路径,缓存大小100Mb
                    Cache cache = new Cache(new File(CreditApplication.getContext().getCacheDir(), "HttpCache"),
                            1024 * 1024 * 100);

                    mOkHttpClient = new OkHttpClient.Builder()
                            .cache(cache)
                            .addInterceptor(mRewriteCacheControlInterceptor)
                            .addNetworkInterceptor(mRewriteCacheControlInterceptor)
                            .addInterceptor(interceptor)
                            .retryOnConnectionFailure(true)
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .readTimeout(60,TimeUnit.SECONDS)
                            .writeTimeout(60,TimeUnit.SECONDS)
                            .build();
                }
            }
        }
    }

    // 云端响应头拦截器,用来配置缓存策略
    private Interceptor mRewriteCacheControlInterceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtil.isNetworkConnected()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }

            okhttp3.Response originalResponse =  chain.proceed(request);
            if (NetworkUtil.isNetworkConnected()) {
                //有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
                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=" + CACHE_STALE_LONG)
                        .removeHeader("Pragma").build();
            }
        }
    };

}

 

 

个人使用到其他相关jar包:

 

 

okhttp与okio.zip(内包含两个jar包)  okio-1.8.0.jar   okhttp-3.3.1.jar

gson-2.7.jar

retrofit-2.1.0.jar

 

 

 

 

 

你可能感兴趣的:(android知识)