Retrofit網路攔截器工具類
阿新 • • 發佈:2019-01-22
先導依賴
//網路請求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<User> 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<String, SPUtil> 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<String, SPUtil>();
}
// 先獲取 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<String, Object> map) {
Set<String> 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<Activity> mTopActivityWeakRef;
/* 儲存所有存活的 Activity */
private static List<Activity> mActivityList = new LinkedList<Activity>();
/* 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<Activity>();
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<Activity>
*/
@RequiresApi(api = Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static List<Activity> 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, "需要儲存的資料");