准备做小说APP的时候抓了挺多小说API,然后发现接口的域名有多个,各种查资料最后解决了多个域名请求的问题,现在记录一下
先在请求头添加okhttpclient拦截器,捕获添加的Headers,然后修改baseURL
public class HttpHeaderInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
// 配置请求头
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(REQUEST_PATH);
} else if ("test2".equals(headerValue)) {
newBaseUrl = HttpUrl.parse(REQUEST_PATH_1);
} else {
newBaseUrl = oldHttpUrl;
}
//重建新的HttpUrl,修改需要修改的url部分
HttpUrl newFullUrl = oldHttpUrl.newBuilder()
.scheme("http")//更换网络协议
.host(newBaseUrl.host())//更换主机名
.port(newBaseUrl.port())//更换端口
.build();
//重建这个request,通过builder.url(newFullUrl).build();
// 然后返回一个response至此结束修改
Log.e("Url", "intercept: " + newFullUrl.toString());
return chain.proceed(builder.url(newFullUrl).build());
}
return chain.proceed(request);
}
}
第二步
在okhttpclient中设置
最后在service代码中添加@Headers():