Retrofit動態切換baseUrl

說明:對於一些功能,須要多個BaseURl來請求不一樣服務器地址的api,我不可能有幾個BaseURl,我就實例化幾個Retrofit實例。這樣作很不科學,要是BaseURl有上百個那個工做量是無法去估計的。爲了解決這個問題方法以下:java

運用應用攔截器Interceptor,來獲取到app到okhttp中間層的request,對它進行修改、處理。api

步驟以下:bash

這是兩個api的BaseUrl服務器

public class Api {
 
    public static final String base_url = "http://172.0.0.92:8080/";
    public static final String base_url_mdffx = "http://11.254.16.19/";
}
複製代碼

在RetrofitService(個人命名爲:IRxJavaService)中要對接口配置@Headers({"key:value"})app

public interface IRxjavaService {
 
    @Headers({"urlname:manage"})
    @POST("members/auth")
    Observable<LoginBean> doLogin(@Body RequestBody requestBody);
 
    @Headers({"urlname:mdffx"})
    @FormUrlEncoded
    @POST("login")
    Observable<LoginMdffxBean> doLoginMdffx(@Field("username") String username,@Field("password") String password);
 
 
    @Headers({"urlname:manage"})
    @GET("members/datas")
    Observable<TongjiDataBean> doData(@Query("type") int type,@Query("params") int params);
}
複製代碼

添加應用攔截器以下:(配置OkhttpClient的方法)ide

public OkHttpClient getokhttpClient() {
        if (httpClient == null) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient = new OkHttpClient.Builder()
                    //處理多BaseUrl,添加應用攔截器
                    .addInterceptor(new MoreBaseUrlInterceptor())
                    //添加頭部信息
                    .addInterceptor(new AddHeadersInterceptor())
                    .addNetworkInterceptor(httpLoggingInterceptor)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .build();
        }
        return httpClient;
    }
複製代碼

定義一個攔截器ui

public class MoreBaseUrlInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //獲取原始的originalRequest
        Request originalRequest = chain.request();
        //獲取老的url
        HttpUrl oldUrl = originalRequest.url();
        //獲取originalRequest的建立者builder
        Request.Builder builder = originalRequest.newBuilder();
        //獲取頭信息的集合如:manage,mdffx
        List<String> urlnameList = originalRequest.headers("urlname");
        if (urlnameList != null && urlnameList.size() > 0) {
            //刪除原有配置中的值,就是namesAndValues集合裏的值
            builder.removeHeader("urlname");
            //獲取頭信息中配置的value,如:manage或者mdffx
            String urlname = urlnameList.get(0);
            HttpUrl baseURL=null;
            //根據頭信息中配置的value,來匹配新的base_url地址
            if ("manage".equals(urlname)) {
                baseURL = HttpUrl.parse(Api.base_url);
            } else if ("mdffx".equals(urlname)) {
                baseURL = HttpUrl.parse(Api.base_url_mdffx);
            }
            //重建新的HttpUrl,須要從新設置的url部分
            HttpUrl newHttpUrl = oldUrl.newBuilder()
                    .scheme(baseURL.scheme())//http協議如:http或者https
                    .host(baseURL.host())//主機地址
                    .port(baseURL.port())//端口
                    .build();
            //獲取處理後的新newRequest
            Request newRequest = builder.url(newHttpUrl).build();
            return  chain.proceed(newRequest);
        }else{
            return chain.proceed(originalRequest);
        }
 
    }
}
複製代碼
相關文章
相關標籤/搜索