1.一般一個(gè)應(yīng)用都只創(chuàng)建一個(gè)Retrofit實(shí)例唬党,但是當(dāng)碰到需要的網(wǎng)絡(luò)請求的baseUrl不止一個(gè)的時(shí)候驶拱,就要考慮如何給retrofit對象根據(jù)不同的請求接口更換不同的baseUrl了。
2.實(shí)現(xiàn)方法如下
companion object{
private const val DEFAULT_TIME:Long=30*1000
private var okHttpClient=OkHttpClient.Builder().connectTimeout(DEFAULT_TIME,TimeUnit.MILLISECONDS)
.writeTimeout(DEFAULT_TIME,TimeUnit.MILLISECONDS).readTimeout(DEFAULT_TIME,TimeUnit.MILLISECONDS).addInterceptor(
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC)
).addInterceptor(ChangeBaseUrlInterceptor())
.retryOnConnectionFailure(true).build()
private var retrofit: Retrofit = Retrofit.Builder().client(okHttpClient)
.baseUrl(Constants.BaseUrl) //設(shè)置網(wǎng)絡(luò)請求的Url地址
.addConverterFactory(GsonConverterFactory.create()) //設(shè)置數(shù)據(jù)解析器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
@JvmStatic
fun isNetworkAvailable(): Boolean {
val connectivity = AbsApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (connectivity == null) {
return false
} else {
val info = connectivity.allNetworkInfo
if (info != null) {
for (i in info.indices) {
if (info[i].state == NetworkInfo.State.CONNECTED) {
return true
}
}
}
}
return false
}
@JvmStatic
fun isNetworkOnWifi(): Boolean {
val connectivity =
AbsApplication.getInstance().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (connectivity != null) {
val info = connectivity.allNetworkInfo
if (info != null) {
for (i in info.indices) {
if (info[i].typeName == "WIFI" && info[i].isConnected) {
return true
}
}
}
}
return false
}
fun <T> getApiService(reqService: Class<T>): T {
return retrofit!!.create(reqService)
}
}
3.API Server 接口定義如下
interface ApiService {
@Headers("domin:login")
@GET("values/5")
fun getRetrofit(): Call<BaseResponse<DemoBean>>
@Headers("domin:loginother")
@GET("values/5")
fun getRetrofitObserver(): Observable<BaseResponse<DemoBean>>
@POST
@Headers("Content-Type:application/json;charset=utf-8")
fun getAnswerObserver(@Url url:String,@Body body: RequestBody): Observable<Answer>
@POST
@Headers("Content-Type:application/json;charset=utf-8")
fun messagePush(@Url url: String,@Body body:RequestBody):Observable<PushResult>
@GET("/session")
fun getSession():Observable<ResponseBody>
}
這幾個(gè)接口的baseUrl都是不一樣的晌纫,怎么區(qū)分呢,通過給接口添加注解锹漱,設(shè)置其請求頭屬性domin的值
下面看一下自定義攔截器是怎么根據(jù)請求頭的domin屬性更換為每個(gè)接口更換baseUrl的
object URLConstant{
const val BASE_URL = "https://login.weixin.qq.com"
const val BASE_LOGIN_URL = "https://wx.qq.com"
const val BASE_LOGIN_OTHER_URL = "https://wx2.qq.com"
const val LOGIN_OTHER = "loginother"
const val LOGIN = "login"
const val DOMAIN = "domain"
}
class ChangeBaseUrlInterceptor :Interceptor{
override fun intercept(chain: Interceptor.Chain): Response {
//獲取request
var request=chain.request()
//從request中獲取原有的HttpUrl實(shí)列 oldHttpUrl
var oldHttpUrl=request.url()
//獲取request的創(chuàng)建者
var builder=request.newBuilder()
//從request中獲取headers 通過給定的建的url_name
var headerValues=request.headers(URLConstant.DOMAIN)
if(headerValues!=null&&headerValues.size>0) {
builder.removeHeader(URLConstant.DOMAIN)
var headValue = headerValues[0]
var newBaseUrl: HttpUrl?
newBaseUrl = when (headValue) {
URLConstant.LOGIN -> {
HttpUrl.parse(URLConstant.BASE_LOGIN_URL)
}
URLConstant.LOGIN_OTHER -> {
HttpUrl.parse(URLConstant.BASE_LOGIN_OTHER_URL)
}
else -> {
HttpUrl.parse(URLConstant.BASE_URL)
}
}
newBaseUrl?.run {
var newHttpUrl =
oldHttpUrl.newBuilder().scheme(scheme()).host(host())
.port(port()).build()
return chain.proceed(builder.url(newHttpUrl).build())
}
}
return chain.proceed(request)
}
}
這是一個(gè)自定義的網(wǎng)絡(luò)請求攔截器毕泌,在創(chuàng)建Retrofit對象的時(shí)候已經(jīng)把攔截器設(shè)置給了Retrofit,那么網(wǎng)絡(luò)請求就會分發(fā)到這個(gè)攔截器,這個(gè)攔截器接收到網(wǎng)絡(luò)請求之后撼泛,就會根據(jù)需求對網(wǎng)絡(luò)請求做一些處理,然后再通過請求鏈把這個(gè)網(wǎng)絡(luò)請求再向下一個(gè)攔截器分發(fā)愿题。這個(gè)過程使用了責(zé)任鏈的設(shè)計(jì)模式,就是當(dāng)一個(gè)任務(wù)下達(dá)之后潘酗,從上一級交由下一級處理,上一級可以根據(jù)實(shí)際情況是攔截任務(wù)自己處理還是繼續(xù)分發(fā)給下一級琐脏,這個(gè)任務(wù)最終會被某一級處理掉或者都無法處理被拋棄掉囚灼,這個(gè)就和Android的view事件分發(fā)機(jī)制的原理是一樣的祭衩。
Http請求采用這種責(zé)任鏈模式的好處是網(wǎng)絡(luò)請求可以分層處理,每一層只實(shí)現(xiàn)某一特定功能即可掐暮,這樣對整個(gè)過程進(jìn)行了解耦,易于理解路克。Retrofit請求更換baseUrl就是這樣實(shí)現(xiàn)的