拦截器原理

public class RetryAndChangeIpInterceptor implements Interceptor {

@Override
public Response intercept(Chain chain) throws IOException {
通过chain 来获取url和request
HttpUrl httpUrl = chain.request().url();
String url = httpUrl.toString();
//根据获取的请求url获取域名: protocol,host,port
String host = getHostByUrl(httpUrl.url());
//截取后边的url
String relativeUrl = url.replace(host, "");
Response response = null;
Request request = chain.request();

Request.Builder requestBuilder;
requestBuilder = request.newBuilder()
.url(url)
.headers(request.headers());

request = requestBuilder.build();

try {
response = chain.proceed(request);这句话是okhttp执行请求的核心,有这句话就再执行请求然后 获取respons结果
if (response != null) {
code = response.code(); 获取请求返回的code
}
connectTime = 0; 记录重连次数 方便下边使用
} catch (Exception e) {
throw e;
}

上边是正常的请求,获取code,code不正确的时候,请求异常的时候,进行下边步骤

//切换使用中域名的条件:当你使用中请求出错,一般就是403 502报错的时候,你获取到了code码,然后进行切换okhttp的请求request:
while (
connectTime < 3
&& AgPreInfoMananger.getInstance().isNeedRetry(host) 这个是有一些请求不用让他切域名
&& (code < 200
|| code > 500)
) {
Host randomHost = AXXXXXr.getInstance().getHost();//这个方法你自己写来获取一个可用的域名 里面有ping或者一些自己加的筛选条件 Host是一个实体类 域名的,随便自己定义就是
if (randomHost != null) {
AgPreInfoMananger.getInstance().setNewHost(randomHost); 获取那个域名设置进去,参考okhttp设置url
host = randomHost.domain;
} else {
return response;
}
下边是设置一下域名的格式 如添加斜杠或者加上api之类
if (!host.endsWith("/")) {
host = host + "/";
}
String urlPath = host + relativeUrl;
requestBuilder = request.newBuilder()
.url(urlPath)
.headers(request.headers());
这里重新组建一个request:
request = requestBuilder.build();
try {
response = chain.proceed(request);
} catch (Exception e) {
throw e;
}
return response;
}
============================================================================================

}}

以上一个拦截器就完成了 需要你自己设置拦截器到okhttp

配置OkHttpClient

OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new RetryAndChangeIpInterceptor())//添加失败重试及重定向拦截器
下边按照你自己的网络请求设置 不一定要 自己删减
.connectTimeout(8, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.build();
————————————————

你可能感兴趣的:(拦截器原理)