Retrofit、OkHttp域名切换
使用1.在客户端请求对象设置域名切换拦截器
OkHttpClient httpClient = new OkHttpClient.Builder() .addInterceptor(new DomainSwitchInterceptor()) .build();
2.在接口类对应方法添加如下注解:
@Headers("domain:http://47.108.248.71:8209")
代码
复制项目即用
import java.io.IOException;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class DomainSwitchInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
return chain.proceed(buildRequest(chain));
}
public Request buildRequest(Chain chain) {
Request request = chain.request();
HttpUrl httpUrl = request.url();
String domain = request.header("domain");
if (domain != null && domain.length() > 0) {
//替换服务器
HttpUrl domainUrl = HttpUrl.parse(domain);
HttpUrl newUrl = httpUrl.newBuilder().scheme(domainUrl.scheme()).host(domainUrl.host()).port(domainUrl.port()).build();
//构建新的请求方式
Request.Builder builder = request.newBuilder();
builder.url(newUrl);
request = builder.build();
}
return request;
}
}



