Retrofit用Interceptor实现内外网接口自动切换访问(在内网IP访问失败的时候.访问外网接口)

本文介绍如何使用Retrofit和Interceptor实现在内网IP访问失败时自动切换到外网接口的功能。通过自定义拦截器RetryAndChangeIpInterceptor,在请求失败时更换BaseUrl,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Retrofit用Interceptor实现内外网接口自动切换访问(在内网IP访问失败的时候.访问外网接口)


  主要项目里面需求有2个baseurl,必须要能够根据用户的网络状况进行baseurl的重新定向,查找了很多博文,发现retrofit实现interceptor做重定向的博客很少,将自己的成果分享下.

1.依赖

    compile 'com.google.code.gson:gson:2.4'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    compile 'com.squareup.okhttp3:okhttp:3.4.2'
    compile group: 'com.squareup.okhttp3', name: 'okhttp-urlconnection', version: '3.3.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'com.github.bumptech.glide:okhttp3-integration:1.4.0@aar'

依赖方面主要就是OKHTTP3和retrofit2,其余部分并不是很重要,可以忽略.

2.具体代码

拦截器代码

import com.orhanobut.logger.Logger;
import com.sia.app.dagger2.global.utils.FramePerfUtil;

import java.io.IOException;

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

/**
 * 切换内网和外网的拦截器
 */
class RetryAndChangeIpInterceptor implements Interceptor {

    private final FramePerfUtil mFramePer;
    //这里的url定义不是很规范,可以的话请自己定义一个集合之类的直接通过集合来传比较合适
    private static final String INNER_IP = RetrofitHelper.INNER_IP;
    private static final String COMMON_IP = RetrofitHelper.COMMON_IP;
    private final int mRetryTimes;
    //retrytimes 重试次数
    RetryAndChangeIpInterceptor(int retryTimes) {
        mRetryTimes = retryTimes;
        mFramePer = FramePerfUtil.getFramePer();
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        //这里做了url的判断来保存sp里面的内外网标识,访问2次成功就更改一下,成功就不进行操作
        Request request = chain.request();
        Response response = doRequest(chain, request);
        int tryCount = 0;
        String url = request.url().toString();
        while (response == null && tryCount < mRetryTimes) {
            if (url.contains(INNER_IP)) {
                url = url.replace(INNER_IP, COMMON_IP);
                mFramePer.setIsInnerIP("false");
            } else {
                url = url.replace(COMMON_IP, INNER_IP);
                mFramePer.setIsInnerIP("true");
            }
            Request newRequest = request.newBuilder().url(url).build();
            tryCount++;
            //这里在为空的response的时候进行请求
            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) {
            Logger.e(e.toString());
        }
        return response;
    }
    }

两个ip地址为

static final String INNER_IP = "http://10.169.1.8/";
static final String COMMON_IP = "http://116.239.5.6:6217/"; 

定义retrofit

        OkHttpClient client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)
                .addInterceptor(new RetryAndChangeIpInterceptor(2))
                .build();
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl)
                .addConverterFactory(SoapConverterFactory.create())
                .client(client)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return retrofit.create(HttpApi.class);
    }

具体接口部分略过
最后看下接口访问的log
这里写图片描述
这里就是完整的一个自动切换baseurl的retrofit请求了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值