[desc]:添加请求类别能力,能够分组预置

[author]:Alex Wang
master
yimiao 3 years ago
parent 673a58d6e7
commit a6a7b80b73

@ -24,7 +24,9 @@ import com.common.commonlibtest.bean.ArticlesResponse;
import com.common.commonlibtest.bean.CollectionResponse;
import com.common.commonlibtest.bean.LoginResponse;
import com.common.commonlibtest.manager.CollectionLoader;
import com.common.commonlibtest.manager.CookieInterceptor;
import com.common.commonlibtest.manager.InternetLoader;
import com.common.commonlibtest.manager.LoaderType;
import com.common.commonlibtest.manager.LoginLoader;
import com.common.commonlibtest.viewpagerlayoutmanager.VariousRvDemoActivity;
import com.yinuo.commonlibtest.R;
@ -35,6 +37,7 @@ import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Cookie;
import okhttp3.Headers;
public class DemoActivity extends AppCompatActivity {
@ -96,17 +99,15 @@ public class DemoActivity extends AppCompatActivity {
});
binding.loginBtn.setOnClickListener(l -> {
RequestHeadInterceptor.Builder builder = new RequestHeadInterceptor.Builder();
CommonInterceptorManager.INSTANCE.addInterceptorByType(builder.build(), true);
CommonInterceptorManager.INSTANCE.addInterceptorByType(new CookieInterceptor());
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");
CookieInterceptor interceptor = (CookieInterceptor) CommonInterceptorManager.INSTANCE.getInterceptorsByType(
LoaderType.LOGIN.getType(), LoaderType.LOGIN.getKey());
interceptor.getMHeaderHashMap().put("Cookie",
"loginUserName_wanandroid_com=wang11;" +
"token_pass_wanandroid_com=6fbec4fe15d69af8b4531171798f3926;" +

@ -4,26 +4,11 @@ import com.common.commonlib.net.BaseObserve
import com.common.commonlib.net.callback.RequestCallBack
import com.common.commonlibtest.bean.CollectionResponse
import io.reactivex.rxjava3.core.Observable
import okhttp3.Interceptor
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Path
class CollectionLoader : BaseObserve<CollectionLoader.CollectionApi> {
var myApi: CollectionApi? = null
var myInterceptorApi : CollectionApi? = null
constructor() : super(CollectionApi::class.java)
constructor(interceptors: List<Interceptor>) : super(CollectionApi::class.java, interceptors)
init {
myApi = initService(CollectionApi::class.java)
}
fun init(interceptors: List<Interceptor>) {
myApi = initService(CollectionApi::class.java)
myInterceptorApi = initService(CollectionApi::class.java, interceptors)
}
class CollectionLoader : BaseObserve<CollectionLoader.CollectionApi>(CollectionApi::class.java) {
fun getCollections(pageName: Int, callBack: RequestCallBack<CollectionResponse>) {
observe(api.getCollections(pageName), callBack)
@ -34,4 +19,8 @@ class CollectionLoader : BaseObserve<CollectionLoader.CollectionApi> {
@GET("/lg/collect/list/{pageNum}/json")
fun getCollections(@Path("pageNum") pageNum: Int): Observable<CollectionResponse>
}
override fun getType(): String {
return LoaderType.LOGIN.type
}
}

@ -0,0 +1,13 @@
package com.common.commonlibtest.manager
import com.common.commonlib.net.interceptor.RequestHeadInterceptor
class CookieInterceptor : RequestHeadInterceptor() {
override fun getType(): String {
return LoaderType.LOGIN.type
}
override fun getKey(): String {
return LoaderType.LOGIN.key
}
}

@ -0,0 +1,5 @@
package com.common.commonlibtest.manager
enum class LoaderType(val type: String, val key: String) {
LOGIN("login", "cookie")
}

@ -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.interfaces.ITypedCommon
import com.common.commonlib.net.manager.RequestManager
import com.google.gson.JsonParseException
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
@ -25,15 +26,15 @@ import javax.net.ssl.SSLHandshakeException
* @author wangym
* @since 2021/7/28
*/
open class BaseObserve<T> {
open class BaseObserve<T> : ITypedCommon {
var api: T
constructor(clazz: Class<T>) {
api = RequestManager.create(clazz)
api = RequestManager.create(clazz, null, getType())
}
constructor(clazz: Class<T>, interceptors: List<Interceptor>) {
api = RequestManager.create(clazz, interceptors)
api = RequestManager.create(clazz, interceptors, getType())
}
/**
@ -43,13 +44,6 @@ open class BaseObserve<T> {
return api
}
/**
* 初始化服务类
*/
fun initService(clazz: Class<T>): T {
return RequestManager.create(clazz)
}
/**
* 调用接口
* @param observable 可订阅
@ -83,13 +77,6 @@ open class BaseObserve<T> {
})
}
/**
* 初始化服务类
*/
fun initService(clazz: Class<T>, interceptors: List<Interceptor>): T {
return RequestManager.create(clazz, interceptors)
}
/**
* 处理错误
* @param e 异常
@ -130,4 +117,8 @@ open class BaseObserve<T> {
const val SERVICE_UNAVAILABLE = 503
const val GATEWAY_TIMEOUT = 504
}
override fun getType(): String {
return BaseObserve<T>::javaClass.name
}
}

@ -1,25 +0,0 @@
package com.common.commonlib.net;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Interceptor;
public class CommonLoader<T> extends BaseObserve<T> {
public CommonLoader(@NonNull Class<T> clazz) {
this(clazz, getBaseInterceptors());
}
public CommonLoader(@NonNull Class<T> clazz, @NonNull List<? extends Interceptor> interceptors) {
super(clazz, interceptors);
}
private static List<? extends Interceptor> getBaseInterceptors() {
List<Interceptor> interceptors = new ArrayList<>();
//interceptors.add(new SessionExpiredInterceptor());
return interceptors;
}
}

@ -1,5 +1,6 @@
package com.common.commonlib.net.interceptor
import com.common.commonlib.net.interfaces.ITypedCommon
import okhttp3.Interceptor
/**
@ -8,14 +9,18 @@ import okhttp3.Interceptor
* @author Alex Wang
* @since 2022-2-24
*/
abstract class CommonInterceptor : Interceptor {
abstract class CommonInterceptor : Interceptor, ITypedCommon {
/**
* 获取拦截器类型
*/
abstract fun getType(): String
override fun getType(): String {
return CommonInterceptor::class.java.simpleName
}
/**
* 获取拦截器key
*/
abstract fun getKey(): String
open fun getKey(): String {
return CommonInterceptor::class.java.simpleName
}
}

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

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

@ -0,0 +1,14 @@
package com.common.commonlib.net.interfaces
/**
* 获取请求类别基础接口
*
* @author Alex Wang
* @since 2022-2-25
*/
interface ITypedCommon {
/**
* 获取请求类别
*/
fun getType(): String
}

@ -17,11 +17,6 @@ object CommonInterceptorManager {
*/
private val mInterceptors: HashMap<String, HashMap<Any, CommonInterceptor>> = HashMap()
/**
* 需要被预置的拦截器
*/
val presetRequireTypes: ArrayList<String> = ArrayList()
/**
* 通过类型获取该类型拦截器列表
*
@ -44,13 +39,6 @@ object CommonInterceptorManager {
return mInterceptors[type]?.get(key)
}
/**
* 获取需要预置类型的拦截器
*/
fun getInterceptorsByRequiredTypeList(): HashMap<Any, CommonInterceptor> {
return getInterceptorsByTypeList(presetRequireTypes)
}
/**
* 通过类型列表获取通用拦截器
* @param typeList 拦截器类型
@ -72,7 +60,7 @@ object CommonInterceptorManager {
*
* @param interceptor 拦截器
*/
fun addInterceptorByType(interceptor: CommonInterceptor, presetRequired: Boolean) {
fun addInterceptorByType(interceptor: CommonInterceptor) {
val type = interceptor.getType()
val key = interceptor.getKey()
var map = mInterceptors[type]
@ -81,9 +69,6 @@ object CommonInterceptorManager {
mInterceptors[type] = map
}
map[key] = interceptor
if (presetRequired && !presetRequireTypes.contains(type)) {
presetRequireTypes.add(type)
}
}
/**

@ -2,7 +2,6 @@ package com.common.commonlib.net.manager
import com.common.commonlib.log.Logger.d
import com.common.commonlib.net.interceptor.HostInterceptor
import com.common.commonlib.utils.BaseUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
@ -33,29 +32,23 @@ object RequestManager {
private var mRetrofit: Retrofit? = null
private var mRetrofitWithIntercept: Retrofit? = null
private val loggingInterceptor = HttpLoggingInterceptor {
d(TAG, it)
}
/**
* 创建service
* 创建retrofit
*
* @param service 类型
* @param interceptors 拦截器
* @param loaderType 请求类别
*/
fun <T> create(service: Class<T>): T {
init(null)
fun <T> create(service: Class<T>, interceptors: List<Interceptor>?, loaderType: String): T {
init(interceptors, loaderType)
return mRetrofit!!.create(service)
}
/**
* 携带commonInterceptor
*/
fun <T> create(service: Class<T>, interceptors: List<Interceptor>): T {
init(interceptors)
return mRetrofitWithIntercept!!.create(service)
}
private fun init(interceptors: List<Interceptor>?) {
private fun init(interceptors: List<Interceptor>?, loaderType: String) {
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
builder.connectTimeout(defaultTimeOut, TimeUnit.SECONDS)
builder.readTimeout(defaultReadTimeOut, TimeUnit.SECONDS)
@ -63,40 +56,30 @@ object RequestManager {
// 动态HOST替换拦截器
builder.addInterceptor(HostInterceptor())
// 添加通用拦截器
val interceptorList = CommonInterceptorManager.getInterceptorsByRequiredTypeList()
if (interceptorList.isNotEmpty()) {
val interceptorList = CommonInterceptorManager.getInterceptorsByType(loaderType)
if (!interceptorList.isNullOrEmpty()) {
d(TAG, "got common interceptor list")
for (item in interceptorList.values) {
builder.addInterceptor(item)
}
}
if (!BaseUtils.isListEmpty(interceptors)) {
for (intercept in interceptors!!) {
// 添加接口自定义的拦截器
if (!interceptors.isNullOrEmpty()) {
for (intercept in interceptors) {
builder.addInterceptor(intercept)
}
// 添加日志拦截器
loggingInterceptor.level = logLevel
builder.addInterceptor(loggingInterceptor)
}
mRetrofitWithIntercept = Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www")
.build()
} else {
// 添加日志拦截器
loggingInterceptor.level = logLevel
builder.addInterceptor(loggingInterceptor)
// 添加日志拦截器 日志拦截器,需要添加在所有拦截器之后
loggingInterceptor.level = logLevel
builder.addInterceptor(loggingInterceptor)
mRetrofit = Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www")
.build()
}
mRetrofit = Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www")
.build()
}
/**

Loading…
Cancel
Save