项目中使用Retrofit进行请求时,后台接口的域名有多个,现记录一下,以备后面使用:
api接口中有两个baseurl:
public static String baseUrl = "https://192.168.1.1/";
public static String sfbaseUrl = "http://192.168.1.2/";
第一步、在service代码中添加@Headers():
@Headers("urlname:test1")
@GET("地址1")
Observable<BaseResponse<List<Bean>>> getHData(@QueryMap Map<String, String> map);
@Headers("urlname:test2")
@GET("地址2")
Observable<BaseResponse<List<Bean>>> getJData(@QueryMap Map<String, String> map);
第二步、添加okhttpclient拦截器,捕获添加的Headers,然后修改baseURL
public class BaseUrlInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
//获取request
Request request = chain.request();
//从request中获取原有的HttpUrl实例oldHttpUrl
HttpUrl oldHttpUrl = request.url();
//获取request的创建者builder
Request.Builder builder = request.newBuilder();
//从request中获取headers,通过给定的键url_name
List<String> headerValues = request.headers("urlname");
if (headerValues != null && headerValues.size() > 0) {
//如果有这个header,先将配置的header删除,因此header仅用作app和okhttp之间使用
builder.removeHeader("urlname");
//匹配获得新的BaseUrl
String headerValue = headerValues.get(0);
HttpUrl newBaseUrl = null;
if ("test1".equals(headerValue)) {
newBaseUrl = HttpUrl.parse(BASE_URL1);
}else if ("test2".equals(headerValue)) {
newBaseUrl = HttpUrl.parse(BASE_URL2);
}else{
newBaseUrl = oldHttpUrl;
}
//重建新的HttpUrl,修改需要修改的url部分
HttpUrl newFullUrl = oldHttpUrl
.newBuilder()
.scheme("https")//更换网络协议
.host(newBaseUrl.host())//更换主机名
.port(newBaseUrl.port())//更换端口
.removePathSegment(0)//移除第一个参数
.build();
//重建这个request,通过builder.url(newFullUrl).build();
// 然后返回一个response至此结束修改
Log.e("Url", "intercept: "+newFullUrl.toString());
return chain.proceed(builder.url(newFullUrl).build());
}
return chain.proceed(request);
}
}
代码中的BASE_URL1和BASE_URL2是你的两个不用域名地址;
第三步、在okhttpclient中设置
//创建一个OkHttpClient并设置超时时间
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(READ_TIME_OUT, TimeUnit.MILLISECONDS)
.connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS)
.addInterceptor(mRewriteCacheControlInterceptor)//没网的情况下
.addNetworkInterceptor(mRewriteCacheControlInterceptor)//有网的情况下
.addInterceptor(new BaseUrlInterceptor())
.addInterceptor(logInterceptor)
.cache(cache)
.build();
最后在Retrofit中设置client,这样就全部ok了,
感谢几篇文章:
https://blog.csdn.net/qq_36707431/article/details/77680252
https://blog.csdn.net/lxj1137800599/article/details/81144583