Android Retrofit、OkHttp域名切换

Android Retrofit、OkHttp域名切换,第1张

Android Retrofit、OkHttp域名切换 DomainSwitchInterceptor

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;
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5682677.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存