[desc]:添加通用拦截器

[author]:wangyimiao
master
yimiao 3 years ago
parent 61b2b16776
commit 23d701417d

@ -12,8 +12,10 @@ import com.common.commonlib.image.loader.ImageLoader;
import com.common.commonlib.log.Logger;
import com.common.commonlib.net.callback.RequestNoResultCallBack;
import com.common.commonlib.net.callback.RequestResultCallBack;
import com.common.commonlib.net.interceptor.CommonInterceptor;
import com.common.commonlib.net.interceptor.RequestHeadInterceptor;
import com.common.commonlib.net.interceptor.ResponseHeadInterceptor;
import com.common.commonlib.net.manager.CommonInterceptorManager;
import com.common.commonlib.serialport.SerialPortUtil;
import com.common.commonlib.utils.BaseUtils;
import com.common.commonlib.utils.FTPUtils;
@ -79,12 +81,7 @@ public class DemoActivity extends AppCompatActivity {
binding.clearBtn.setOnClickListener(l -> ImageLoader.INSTANCE.clearAllCache(DemoActivity.this));
binding.btn.setOnClickListener(l -> {
List<RequestHeadInterceptor> interceptors = new ArrayList<>();
RequestHeadInterceptor.Builder builder = new RequestHeadInterceptor.Builder();
builder.addHeadParams("Cookie",
"loginUserName_wanandroid_com=wang11;token_pass_wanandroid_com=6fbec4fe15d69af8b4531171798f3926;loginUserName=wang11;token_pass=6fbec4fe15d69af8b4531171798f3926");
interceptors.add(builder.build());
CollectionLoader loader = new CollectionLoader(interceptors);
CollectionLoader loader = new CollectionLoader();
loader.getCollections(0, new RequestNoResultCallBack<CollectionResponse>() {
@Override
public void onError(@Nullable String error) {
@ -99,10 +96,22 @@ public class DemoActivity extends AppCompatActivity {
});
binding.loginBtn.setOnClickListener(l -> {
RequestHeadInterceptor.Builder builder = new RequestHeadInterceptor.Builder();
CommonInterceptorManager.INSTANCE.addInterceptorByType(builder.build(), true);
List<ResponseHeadInterceptor> interceptors = new ArrayList<>();
interceptors.add(new ResponseHeadInterceptor(response -> {
Headers headers = response.headers();
List<String> cookies = headers.values("Set-Cookie");
RequestHeadInterceptor interceptor =
(RequestHeadInterceptor) CommonInterceptorManager.INSTANCE.getInterceptorsByType(
"RequestHeadInterceptor", "RequestHeadInterceptor");
interceptor.getMHeaderHashMap().put("Cookie",
"loginUserName_wanandroid_com=wang11;" +
"token_pass_wanandroid_com=6fbec4fe15d69af8b4531171798f3926;" +
"loginUserName=wang11;" +
"token_pass=6fbec4fe15d69af8b4531171798f3926");
}));
new LoginLoader(interceptors).login("wang11", "wang456852", new RequestNoResultCallBack<LoginResponse>() {
@Override

@ -15,9 +15,9 @@ com.common.commonlib.image.module.OkHttpLibraryGlideModule -> com.common.commonl
# {"id":"sourceFile","fileName":"OkHttpLibraryGlideModule.kt"}
1:1:void <init>():19:19 -> <init>
1:1:void registerComponents(android.content.Context,com.bumptech.glide.Glide,com.bumptech.glide.Registry):23:23 -> registerComponents
com.common.commonlib.net.RequestManager -> a.a:
com.common.commonlib.net.manager.RequestManager -> a.a:
# {"id":"sourceFile","fileName":"RequestManager.kt"}
com.common.commonlib.net.RequestManager INSTANCE -> a
com.common.commonlib.net.manager.RequestManager INSTANCE -> a
1:17:void <clinit>():22:38 -> <clinit>
1:1:void <init>():20:20 -> <init>
1:1:void loggingInterceptor$lambda-0(java.lang.String):39:39 -> a
@ -39,13 +39,13 @@ com.common.commonlib.utils.BaseUtils -> com.common.commonlib.utils.BaseUtils:
# {"id":"sourceFile","fileName":"BaseUtils.kt"}
1:1:void <init>():10:10 -> <init>
1:1:void enableBasicLog():39:39 -> enableBasicLog
2:2:void com.common.commonlib.net.RequestManager.openBasicLog():102:102 -> enableBasicLog
2:2:void com.common.commonlib.net.manager.RequestManager.openBasicLog():102:102 -> enableBasicLog
2:2:void enableBasicLog():39 -> enableBasicLog
1:1:void enableFullLog():32:32 -> enableFullLog
2:2:void com.common.commonlib.net.RequestManager.openFullLog():95:95 -> enableFullLog
2:2:void com.common.commonlib.net.manager.RequestManager.openFullLog():95:95 -> enableFullLog
2:2:void enableFullLog():32 -> enableFullLog
1:1:void enableHeadersLog():46:46 -> enableHeadersLog
2:2:void com.common.commonlib.net.RequestManager.openHeadLog():109:109 -> enableHeadersLog
2:2:void com.common.commonlib.net.manager.RequestManager.openHeadLog():109:109 -> enableHeadersLog
2:2:void enableHeadersLog():46 -> enableHeadersLog
1:1:java.lang.String getExternalStorageDirectory(android.content.Context):25:25 -> getExternalStorageDirectory
1:1:java.lang.String getExternalStoragePath(android.content.Context):21:21 -> getExternalStoragePath

@ -4,6 +4,7 @@ import android.net.ParseException
import android.util.Log
import com.common.commonlib.log.Logger
import com.common.commonlib.net.callback.RequestCallBack
import com.common.commonlib.net.manager.RequestManager
import com.google.gson.JsonParseException
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable

@ -1,7 +1,7 @@
package com.common.commonlib.net.bean
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import kotlinx.parcelize.Parcelize
/**
* 基础响应类

@ -0,0 +1,21 @@
package com.common.commonlib.net.interceptor
import okhttp3.Interceptor
/**
* 通用拦截器基类
*
* @author Alex Wang
* @since 2022-2-24
*/
abstract class CommonInterceptor : Interceptor {
/**
* 获取拦截器类型
*/
abstract fun getType(): String
/**
* 获取拦截器key
*/
abstract fun getKey(): String
}

@ -18,7 +18,7 @@ import java.util.*
* @author wangym
* @since 2021/7/28
*/
class BaseUrlInterceptor : Interceptor {
class HostInterceptor : Interceptor {
/**
* 拦截替换BaseUrl
*/

@ -10,12 +10,20 @@ import okhttp3.Response
* @author wangym
* @since 2021/7/28
*/
class RequestHeadInterceptor : Interceptor {
class RequestHeadInterceptor : CommonInterceptor() {
/**
* 请求头部参数
*/
var mHeaderHashMap: HashMap<String, String> = HashMap()
override fun getType(): String {
return "RequestHeadInterceptor"
}
override fun getKey(): String {
return "RequestHeadInterceptor"
}
/**
* 拦截请求并添加参数
*/

@ -9,7 +9,16 @@ import okhttp3.Response
* @author wangym
* @since 2021/7/28
*/
class ResponseHeadInterceptor(private var callBack: ResponseCallBack?) : Interceptor {
class ResponseHeadInterceptor(private var callBack: ResponseCallBack?) : CommonInterceptor() {
override fun getType(): String {
return "RequestHeadInterceptor"
}
override fun getKey(): String {
return "RequestHeadInterceptor"
}
override fun intercept(chain: Interceptor.Chain): Response {
// 获取响应
val response = chain.proceed(chain.request())

@ -0,0 +1,119 @@
package com.common.commonlib.net.manager
import com.common.commonlib.net.interceptor.CommonInterceptor
/**
* 通用拦截器管理类
* 用于请求的通用拦截器管理
*
* @author Alex Wang
* @since 2022-2-24
*/
object CommonInterceptorManager {
const val TAG = "CommonInterceptorManager"
/**
* 拦截器
*/
private val mInterceptors: HashMap<String, HashMap<Any, CommonInterceptor>> = HashMap()
/**
* 需要被预置的拦截器
*/
val presetRequireTypes: ArrayList<String> = ArrayList()
/**
* 通过类型获取该类型拦截器列表
*
* @param type 拦截器类型
*
* @return 拦截器列表
*/
fun getInterceptorsByType(type: String): Map<Any, CommonInterceptor>? {
return mInterceptors[type]
}
/**
* 通过类型获取该类型拦截器列表
*
* @param type 拦截器类型
*
* @return 拦截器列表
*/
fun getInterceptorsByType(type: String, key: String): CommonInterceptor? {
return mInterceptors[type]?.get(key)
}
/**
* 获取需要预置类型的拦截器
*/
fun getInterceptorsByRequiredTypeList(): HashMap<Any, CommonInterceptor> {
return getInterceptorsByTypeList(presetRequireTypes)
}
/**
* 通过类型列表获取通用拦截器
* @param typeList 拦截器类型
*
* @return 拦截器map
*/
fun getInterceptorsByTypeList(typeList: ArrayList<String>): HashMap<Any, CommonInterceptor> {
val result = HashMap<Any, CommonInterceptor>()
for (item in typeList) {
if (!getInterceptorsByType(item).isNullOrEmpty()) {
result.putAll(getInterceptorsByType(item)!!)
}
}
return result
}
/**
* 添加新的通用拦截器
*
* @param interceptor 拦截器
*/
fun addInterceptorByType(interceptor: CommonInterceptor, presetRequired: Boolean) {
val type = interceptor.getType()
val key = interceptor.getKey()
var map = mInterceptors[type]
if (map.isNullOrEmpty()) {
map = HashMap()
mInterceptors[type] = map
}
map[key] = interceptor
if (presetRequired && !presetRequireTypes.contains(type)) {
presetRequireTypes.add(type)
}
}
/**
* 删除通用拦截器
*
* @param type 请求类型
* @param key 拦截器key
*/
fun removeInterceptorByType(type: String, key: String) {
val map = mInterceptors[type]
if (!map.isNullOrEmpty()) {
map.remove(key)
}
}
/**
* 删除通用拦截器
*
* @param type 请求类型
*/
fun removeInterceptorByType(type: String) {
mInterceptors.remove(type)
}
/**
* 删除通用拦截器
*
* @param interceptor 拦截器
*/
fun removeInterceptorByType(interceptor: CommonInterceptor) {
removeInterceptorByType(interceptor.getType(), interceptor.getKey())
}
}

@ -1,7 +1,7 @@
package com.common.commonlib.net
package com.common.commonlib.net.manager
import com.common.commonlib.log.Logger.d
import com.common.commonlib.net.interceptor.BaseUrlInterceptor
import com.common.commonlib.net.interceptor.HostInterceptor
import com.common.commonlib.utils.BaseUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
@ -43,9 +43,9 @@ object RequestManager {
* 创建service
*/
fun <T> create(service: Class<T>): T {
if (mRetrofit == null) {
// if (mRetrofit == null) {
init(null)
}
// }
return mRetrofit!!.create(service)
}
@ -61,12 +61,20 @@ object RequestManager {
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
builder.connectTimeout(defaultTimeOut, TimeUnit.SECONDS)
builder.readTimeout(defaultReadTimeOut, TimeUnit.SECONDS)
// 动态HOST替换拦截器
builder.addInterceptor(BaseUrlInterceptor())
// 动态HOST替换拦截器
builder.addInterceptor(HostInterceptor())
// 添加日志拦截器
loggingInterceptor.level = logLevel
builder.addInterceptor(loggingInterceptor)
// 添加通用拦截器
val interceptorList = CommonInterceptorManager.getInterceptorsByRequiredTypeList()
if (interceptorList.isNotEmpty()) {
d(TAG, "got common interceptor list")
for (item in interceptorList.values) {
builder.addInterceptor(item)
}
}
if (!BaseUtils.isListEmpty(interceptors)) {
for (intercept in interceptors!!) {

@ -2,7 +2,7 @@ package com.common.commonlib.utils
import android.content.Context
import android.os.Environment
import com.common.commonlib.net.RequestManager
import com.common.commonlib.net.manager.RequestManager
/**
* 基础工具类

Loading…
Cancel
Save