okhttp之自定义Interceptor:请求失败切换IP重试拦截器

尊重他人的劳动成果,转载请标明出处:http://blog.csdn.net/gengqiquan/article/details/52200393, 本文出自:【gengqiquan的博客】

经过一段时间的挣扎,终于把新公司项目的网络框架换成了retrofit,由于项目是有失败重试和重定向需求的,所以需要在新的网络框架上增加这个功能,大家都知道retrofit的网络请求部分是基于okhttp的。这个时候可爱的Interceptor设计就提现出他的好处了,不需要修改其他的代码,直接增加一个拦截器就OK了

实现一个拦截器继承Interceptor(2.0到3.0之前的版本)

public class RetryAndChangeIpInterceptor implements Interceptor {
    String FirstIP;
    String SecondIP;
    int RetryCount;

    public RetryAndChangeIpInterceptor(String firsrIP, String secondIP, int tryCount) {
        FirstIP = firsrIP;
        SecondIP = secondIP;
        RetryCount = tryCount;
    }

    public RetryAndChangeIpInterceptor(String firsrIP, String secondIP) {
        FirstIP = firsrIP;
        SecondIP = secondIP;
        RetryCount = 3;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // try the request
        Response response = chain.proceed(request);
        int tryCount = 0;
        while (!response.isSuccessful() && tryCount <= RetryCount) {
            String url = request.url().toString();
            if (!Util.checkNULL(FirstIP) && !Util.checkNULL(SecondIP)) {//重定向
                if (url.contains(FirstIP)) {
                    url = url.replace(FirstIP, SecondIP);
                } else if (url.contains(SecondIP)) {
                    url = url.replace(SecondIP, FirstIP);
                }
                Request newRequest = response.request().newBuilder().url(url).build();
                Log.d("intercept", "Request is not successful - " + tryCount);
                tryCount++;
                // retry the request
                response = chain.proceed(newRequest);
            } else {
                response = chain.proceed(request);
            }
        }
        return response;
    }
}

3.0及以上版本(取消了httpEngine,采用了纯拦截器递归调用机制)

package com.sunshine.retrofit.interceptor;

import android.util.Log;


import java.io.IOException;
import java.util.List;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 耿 on 2016/8/12.
 */
public class RetryAndChangeIpInterceptor implements Interceptor {
    int RetryCount = 3;
    String FirstIP;
    List<String> SERVERS;

    public RetryAndChangeIpInterceptor(String firsrIP, List<String> sERVERS) {
        FirstIP = firsrIP;
        SERVERS = sERVERS;
        RetryCount = 3;
    }

    public RetryAndChangeIpInterceptor(String firsrIP, List<String> sERVERS, int tryCount) {
        FirstIP = firsrIP;
        SERVERS = sERVERS;
        RetryCount = tryCount;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        // try the request
        Response response = doRequest(chain, request);
        int tryCount = 0;
        String url = request.url().toString();
        while (response == null && tryCount <= RetryCount) {
            url = switchServer(url);
            Request newRequest = request.newBuilder().url(url).build();
            Log.d("intercept", "Request is not successful - " + tryCount);
            tryCount++;
            // retry the request
            response = doRequest(chain, newRequest);
        }
        if (response == null) {
            throw new IOException();
        }
        return response;
    }

    private Response doRequest(Chain chain, Request request) {
        Response response = null;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
        }
        return response;
    }

    private String switchServer(String url) {
        String newUrlString = url;
        if (url.contains(FirstIP)) {
            for (String server : SERVERS) {
                if (!FirstIP.equals(server)) {
                    newUrlString = url.replace(FirstIP, server);
                    break;
                }
            }
        } else {
            for (String server : SERVERS) {
                if (url.contains(server)) {
                    newUrlString = url.replace(server, FirstIP);
                    break;
                }
            }
        }
        return newUrlString;
    }


}

配置OkHttpClient

  OkHttpClient client = new OkHttpClient.Builder()
                    .addInterceptor(new RetryAndChangeIpInterceptor(BASE_URL, SecondIP))//添加失败重试及重定向拦截器

                    .retryOnConnectionFailure(true)//允许失败重试
                    .connectTimeout(8, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .writeTimeout(5, TimeUnit.SECONDS)
                    .build();

我建了一个QQ群(群号:121606151),用于大家讨论交流Android技术问题,有兴趣的可以加下,大家一起进步。

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页