Retrofit+OkHttp+RxJava运行时修改POST请求的URL

在使用Retrofit时,如果我们想变更某个请求的URL,GET请求的话,可以使用@Url 注解,但如果是POST请求,是不能直接这么干的。

我的做法是在Retrofit.create(XXXX.class)之前,给OkHttp添加拦截器,拦截器识别请求header中是否带着我们预先自定义的参数。在请求发起时header中增加key:NEW_HOST_URL,value为将于替换的新地址。

拦截器的代码如下:

/**
 * interceptor to intercept POST request to change request address.
 *
 * GET request: suggest to use {@link Url} on method.
 */
public class PostUrlInterceptor implements Interceptor {

    public static final String NEW_HOST_URL = "NEW_HOST_URL";

    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();
        String newHost = request.header(NEW_HOST_URL);
        if (!TextUtils.isEmpty(newHost)) {
            Request.Builder builder = request.newBuilder();
            HttpUrl httpUrl = request.url();
            String originAddress = httpUrl.scheme() + "://" + httpUrl.host() + ":" + httpUrl.port();
            String requestUrl = httpUrl.url().toString();
            if (requestUrl.startsWith(originAddress)) {
                builder.url(requestUrl.replace(originAddress, newHost));
            }
            request = builder.build();
        }
        return chain.proceed(request);
    }
}

如果header中有这个新的地址,就用它去请求。如果没有则不做拦截。

就这么简单。