Retrofit网络拦截器工具类

先导依赖

//网络请求Retrofit与所用Gson
    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    //Rxjava
    implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
    implementation 'io.reactivex:rxandroid:1.1.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

工具类 AService是Retrifit的Service接口

如果请求头里有一些是需要后期获取的可以用储存值的工具类 来把获取到的值放进去

SPUtil 就是储存的工具类  Keys 是储存类 我会在后边贴出

public class RetrofitUtils {
    private static RetrofitUtils retrofitUtils;
    private final Retrofit retrofit;

    //无参构造
    public RetrofitUtils() {
        //拦截器
        OkHttpClient client = new OkHttpClient.Builder().addNetworkInterceptor(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request().newBuilder()
                        //请求头里面有的话就加上这两个只是举例 
                        .addHeader("apptoken", String.valueOf(SPUtil.getInstance().get(Keys.TOKEN, "")))
                        .addHeader("appType", "univstarUnion")
                        .build();

                return chain.proceed(request);
            }
        }).build();

        
        retrofit = new Retrofit.Builder()
                //这里面放网址地址 网址可以按照需求更改
                //协议,ip地址(:端口号)和路径中的一些相同的路径
                .baseUrl("http://www.baidu.com")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                //使用拦截器
                .client(client)
                .build();

    }

    //单例模式
    public static RetrofitUtils getInstence() {
        if (retrofitUtils == null) {
            synchronized (RetrofitUtils.class) {
                if (retrofitUtils == null) {
                    retrofitUtils = new RetrofitUtils();
                }
            }
        }
        return retrofitUtils;
    }

    //返回一个AService的值 方便m层调用
    public AService getAService() {
        return retrofit.create(AService.class);
    }

}

然后在m层调用时就很短了  

public class AModel implements AContract.Model {


    @Override
    public void set(int id, Call call) {
        //调用工具类
        AService service = RetrofitUtils.getInstence().getAService();
        //其他的就和普通的一样
        Observable sendPost = service.sendPost(id);
        call.get(sendPost);
    }
}

没有写很细  有些地方我没有加详细的注释 应该不难看懂吧 我用的Retrofit+Rxjava+Tmvp  

储存值的工具类SPUtil  直接粘贴就行 这个不用更改  工具类需要另一个工具类 SUtils 

/**
 * SharedPreferences 工具类
 */
@SuppressLint("ApplySharedPref")
public class SPUtil {
    private static final String DEF_FILENAME = "SPUtil";
    private static final int DEF_MODE = Context.MODE_PRIVATE;
    /* 存储所有的 SharedPreferences 实例 */
    private static Map mInstanceMap;
    private static SharedPreferences mSp;
    private static SharedPreferences.Editor mEditor;

    private SPUtil(String fileName, int mode) {
        super();
        mSp = SUtils.getApp().getSharedPreferences(fileName, mode);
        mEditor = mSp.edit();
    }

    public static SPUtil getInstance() {
        return getInstance(DEF_FILENAME, DEF_MODE);
    }

    public static SPUtil getInstance(@NonNull String fileName) {
        return getInstance(fileName, DEF_MODE);
    }

    public static SPUtil getInstance(@NonNull String fileName, @NonNull int mode) {
        if (mInstanceMap == null) {
            mInstanceMap = new HashMap();
        }
        // 先获取 SharedPreferences 实例
        SPUtil manager = mInstanceMap.get(fileName + "_" + mode);
        // 如果获取不到,则重新创建
        if (manager == null) {
            manager = new SPUtil(fileName, mode);
            mInstanceMap.put(fileName + "_" + mode, manager);
        }
        return manager;
    }

    /**
     * 保存单个数据
     *
     * @param key    键值
     * @param object 存储的内容
     */
    public void put(String key, Object object) {
        if (object instanceof String) {
            mEditor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            mEditor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            mEditor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            mEditor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            mEditor.putLong(key, (Long) object);
        } else {
            mEditor.putString(key, object.toString());
        }
        mEditor.commit();
    }

    /**
     * 同时保存多条数据
     *
     * @param map 存储的数据
     */
    public void add(Map map) {
        Set set = map.keySet();
        for (String key : set) {
            Object object = map.get(key);
            if (object instanceof String) {
                mEditor.putString(key, (String) object);
            } else if (object instanceof Integer) {
                mEditor.putInt(key, (Integer) object);
            } else if (object instanceof Boolean) {
                mEditor.putBoolean(key, (Boolean) object);
            } else if (object instanceof Float) {
                mEditor.putFloat(key, (Float) object);
            } else if (object instanceof Long) {
                mEditor.putLong(key, (Long) object);
            } else {
                mEditor.putString(key, object.toString());
            }
        }
        mEditor.commit();
    }

    /**
     * 获取存储的数据
     *
     * @param key    键值
     * @param object 默认返回值
     * @return 存储的内容
     */
    public Object get(String key, Object object) {
        if (object instanceof String) {
            return mSp.getString(key, (String) object);
        } else if (object instanceof Integer) {
            return mSp.getInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            return mSp.getBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            return mSp.getFloat(key, (Float) object);
        } else if (object instanceof Long) {
            return mSp.getLong(key, (Long) object);
        }
        return null;
    }

    /**
     * 根据 key 删除数据
     *
     * @param key 键值
     */
    public void delete(String key) {
        mEditor.remove(key);
        mEditor.commit();
    }

    /**
     * 清除所有的数据
     */
    public void clear() {
        mEditor.clear();
        mEditor.commit();
    }

    public SharedPreferences.Editor getEditor() {
        return mEditor;
    }
}

SUtils  一样不用改

/**
 * @author liyi
 */
public class SUtils {

    @SuppressLint("StaticFieldLeak")
    private static Application mApplication;
    /* 当前处于栈顶的 Activity */
    private static WeakReference mTopActivityWeakRef;
    /* 存储所有存活的 Activity */
    private static List mActivityList = new LinkedList();
    /* Activity 的生命周期 */
    private static Application.ActivityLifecycleCallbacks mLifecycleCallback = new Application.ActivityLifecycleCallbacks() {
        @Override
        public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
            // activity 被创建时,向 Activity 列表中添加 activity
            mActivityList.add(activity);
            setTopActivityWeakRef(activity);
        }

        @Override
        public void onActivityStarted(Activity activity) {

        }

        @Override
        public void onActivityResumed(Activity activity) {

        }

        @Override
        public void onActivityPaused(Activity activity) {

        }

        @Override
        public void onActivityStopped(Activity activity) {

        }

        @Override
        public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(Activity activity) {
            // activity 被销毁时,从 Activity 列表中移除 activity
            mActivityList.remove(activity);
        }
    };

    private SUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 初始化工具类
     *
     * @param app 应用对象
     */
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static void initialize(@NonNull final Application app) {
        mApplication = app;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            if (mActivityList == null) mActivityList = new LinkedList();
            app.registerActivityLifecycleCallbacks(mLifecycleCallback);
        }
    }

    /**
     * 获取应用对象
     *
     * @return Application
     */
    public static Application getApp() {
        if (mApplication != null) {
            return mApplication;
        }
        throw new NullPointerException("you should initialize first");
    }

    /**
     * 设置栈顶的 Activity
     *
     * @param activity
     */
    private static void setTopActivityWeakRef(Activity activity) {
        if (mTopActivityWeakRef == null || mTopActivityWeakRef.get() == null || !mTopActivityWeakRef.get().equals(activity)) {
            mTopActivityWeakRef = new WeakReference<>(activity);
        }
    }

    /**
     * 获取栈顶的 Activity
     *
     * @return Activity
     */
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static Activity getTopActivity() {
        if (mTopActivityWeakRef != null && mTopActivityWeakRef.get() != null) {
            return mTopActivityWeakRef.get();
        } else if (mActivityList != null && mActivityList.size() > 0) {
            return mActivityList.get(mActivityList.size() - 1);
        }
        return null;
    }

    /**
     * 获取 Activity 列表
     *
     * @return List
     */
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static List getActivityList() {
        return mActivityList;
    }

    /**
     * 移除指定的 Activity
     *
     * @param activity
     */
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static void removeActivity(Activity activity) {
        if (mActivityList != null) {
            if (activity != null && !activity.isFinishing()) {
                activity.finish();
            }
            mActivityList.remove(activity);
        }
    }

    /**
     * 移除指定的 Activity
     *
     * @param cls
     */
    @RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public static void removeActivity(Class cls) {
        if (mActivityList != null) {
            for (int i = 0, size = mActivityList.size(); i < size; i++) {
                Activity activity = mActivityList.get(i);
                if (activity.getClass().getName().equals(cls.getName())) {
                    if (!activity.isFinishing()) {
                        activity.finish();
                    }
                    mActivityList.remove(i);
                    break;
                }
            }
        }
    }
}

keys

public class Keys {
    public static final String TOKEN = "token";
}

储存数据的方法

SPUtil.getInstance().put(Keys.TOKEN, "需要储存的数据");

 

你可能感兴趣的:(Retrofit网络拦截器工具类)