author:wangyimiao

desc:添加自定义拦截器API
master
yimiao 3 years ago
parent 843e8ffb27
commit ba79414412

@ -6,12 +6,18 @@ import android.os.Bundle;
import android.util.Log;
import com.common.commonlib.net.RequestCallBack;
import com.common.commonlib.net.interceptor.HttpCommonInterceptor;
import com.common.commonlibtest.bean.ArticlesResponse;
import com.common.commonlibtest.bean.CollectionResponse;
import com.common.commonlibtest.manager.CollectionLoader;
import com.common.commonlibtest.manager.InternetLoader;
import com.yinuo.commonlibtest.databinding.ActivityMainBinding;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
ActivityMainBinding binding;
@ -44,5 +50,29 @@ public class MainActivity extends AppCompatActivity {
}
});
});
binding.btn.setOnClickListener(l -> {
List<HttpCommonInterceptor> interceptors = new ArrayList<>();
HttpCommonInterceptor.Builder builder = new HttpCommonInterceptor.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);
loader.getCollections(0, new RequestCallBack<CollectionResponse>() {
@Override
public void onResult(CollectionResponse result) {
Log.d(TAG, "onResult");
}
@Override
public void onError(@Nullable String error) {
Log.d(TAG, "onError");
}
@Override
public void onComplete() {
Log.d(TAG, "onComplete");
}
});
});
}
}

@ -0,0 +1,15 @@
package com.common.commonlibtest.bean
import android.os.Parcelable
import com.common.commonlib.net.bean.BaseResponse
import kotlinx.android.parcel.Parcelize
@Parcelize
data class CollectionData(var curPage: Int = 0) : Parcelable {
var datas: List<Article>? = null
var offset: Int = 0
var over: Boolean = false
var pageCount: Int = 0
var size: Int = 0
var total: Int = 0
}

@ -0,0 +1,8 @@
package com.common.commonlibtest.bean
import android.os.Parcelable
import com.common.commonlib.net.bean.BaseResponse
import kotlinx.android.parcel.Parcelize
@Parcelize
data class CollectionResponse(var data: CollectionData) : BaseResponse(), Parcelable

@ -0,0 +1,29 @@
package com.common.commonlibtest.manager
import com.common.commonlib.net.BaseObserve
import com.common.commonlib.net.RequestCallBack
import com.common.commonlibtest.bean.CollectionResponse
import io.reactivex.Observable
import okhttp3.Interceptor
import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Path
class CollectionLoader(interceptors: List<Interceptor>) :
BaseObserve<CollectionLoader.CollectionApi>() {
private val api: CollectionApi
init {
api = initService(CollectionApi::class.java, interceptors)
}
fun getCollections(pageName: Int, callBack: RequestCallBack<CollectionResponse>) {
observe(api.getCollections(pageName), callBack)
}
interface CollectionApi {
@Headers("baseurl:debug1")
@GET("/lg/collect/list/{pageNum}/json")
fun getCollections(@Path("pageNum") pageNum: Int): Observable<CollectionResponse>
}
}

@ -8,6 +8,9 @@ import retrofit2.http.GET
import retrofit2.http.Headers
import retrofit2.http.Path
/**
* 网络请求样例
*/
class InternetLoader : BaseObserve<InternetLoader.HomeApi>() {
var homeApi: HomeApi

@ -3,8 +3,7 @@
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
android:layout_height="match_parent">
<TextView
android:id="@+id/tv"
@ -16,4 +15,15 @@
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.599" />
</androidx.constraintlayout.widget.ConstraintLayout>

@ -48,8 +48,8 @@ dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.navigation:navigation-fragment:2.3.0'
implementation 'androidx.navigation:navigation-ui:2.3.0'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.0'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.0'
// kotlin
implementation rootProject.ext.dependencies.kotlin

@ -8,6 +8,7 @@ import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import okhttp3.Interceptor
import org.json.JSONException
import retrofit2.HttpException
import java.net.ConnectException
@ -23,7 +24,11 @@ open class BaseObserve<T> {
* 初始化服务类
*/
fun initService(clazz: Class<T>): T {
return RequestManager.INSTANCE.create(clazz)
return RequestManager.create(clazz)
}
fun initService(clazz: Class<T>, interceptors: List<Interceptor>): T {
return RequestManager.create(clazz, interceptors)
}
/**

@ -2,6 +2,8 @@ package com.common.commonlib.net
import com.common.commonlib.net.interceptor.BaseUrlInterceptor
import com.common.commonlib.net.interceptor.HttpCommonInterceptor
import com.common.commonlib.utils.BaseUtils
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
@ -11,41 +13,63 @@ import java.util.concurrent.TimeUnit
/**
* 网络请求管理器
*/
enum class RequestManager {
INSTANCE;
object RequestManager {
/**
* 默认超时时间
*/
private val defaultTimeOut: Long = 5
private const val defaultTimeOut: Long = 5
/**
* 默认读取超时时间
*/
private val defaultReadTimeOut: Long = 10
private const val defaultReadTimeOut: Long = 10
private var mRetrofit: Retrofit? = null
init {
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
builder.connectTimeout(defaultTimeOut, TimeUnit.SECONDS)
builder.readTimeout(defaultReadTimeOut, TimeUnit.SECONDS)
val commonInterceptor: HttpCommonInterceptor = HttpCommonInterceptor.Builder().build()
builder.addInterceptor(commonInterceptor)
builder.addInterceptor(BaseUrlInterceptor())
mRetrofit = Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www.wanandroid.com")
.build()
}
private var mRetrofitWithIntercept: Retrofit? = null
/**
* 创建service
*/
fun <T> create(service: Class<T>): T {
if (mRetrofit == null) {
init(null)
}
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>?) {
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
builder.connectTimeout(defaultTimeOut, TimeUnit.SECONDS)
builder.readTimeout(defaultReadTimeOut, TimeUnit.SECONDS)
// 动态HOST替换拦截器
builder.addInterceptor(BaseUrlInterceptor())
if (!BaseUtils.isListEmpty(interceptors)) {
for (intercept in interceptors!!) {
builder.addInterceptor(intercept)
}
mRetrofitWithIntercept = Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www.wanandroid.com")
.build()
} else {
mRetrofit = Retrofit.Builder()
.client(builder.build())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://www.wanandroid.com")
.build()
}
}
}

@ -13,7 +13,7 @@ import java.io.BufferedInputStream
import java.util.*
/**
* BaseUrl链接拦截器
* HOST拦截器:动态替换HOST
*/
class BaseUrlInterceptor : Interceptor {
/**

@ -11,7 +11,7 @@ class HttpCommonInterceptor : Interceptor {
/**
* 请求头部参数
*/
var mHeaderHashMap: HashMap<String, String>? = null
var mHeaderHashMap: HashMap<String, String> = HashMap()
/**
* 拦截请求并添加参数
@ -20,8 +20,8 @@ class HttpCommonInterceptor : Interceptor {
val oldRequest: Request = chain.request()
val requestBuilder: Request.Builder = oldRequest.newBuilder()
requestBuilder.method(oldRequest.method, oldRequest.body)
if (mHeaderHashMap != null && mHeaderHashMap!!.size > 0) {
for (item: Map.Entry<String, String> in mHeaderHashMap!!.entries) {
if (mHeaderHashMap.size > 0) {
for (item: Map.Entry<String, String> in mHeaderHashMap.entries) {
requestBuilder.addHeader(item.key, item.value)
}
}

Loading…
Cancel
Save