如何获得OkHttp3重定向URL



是否有办法获得请求的最终URL ?我知道我可以禁用重定向和这个自己,但有没有办法得到当前的URL我正在加载?比如,如果我请求。com,被重定向到b.com,有没有办法得到url b.com的名称呢?

响应对象提供用于获取它的请求和响应链。

要获得最终的URL,在Response上调用request()以获得最终的Request,然后提供您想要的url()

您可以通过调用priorResponse()并查看每个Response关联的Request来跟踪整个响应链。

Builder提供了NetworkInterceptor。下面是一个例子:

        OkHttpClient httpClient = new OkHttpClient.Builder()
            .addNetworkInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    System.out.println("url: " + chain.request().url());
                    return chain.proceed(chain.request());
                }
            })
            .build();
    System.out.println(httpClient.newCall(new Request.Builder().url("http://google.com").build()).execute());

OkHttp3 wiki: Interceptors

您可以在响应头中使用"Location"(参见主题https://stackoverflow.com/a/41539846/9843623)。例子:

{
{
    okHttpClient = new OkHttpClient.Builder()
        .addNetworkInterceptor(new LoggingInterceptor())
        .build();
}
private class LoggingInterceptor implements Interceptor {
    @Override public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        utils.log("LoggingInterceptor", "isRedirect=" + response.isRedirect());
        utils.log("LoggingInterceptor", "responseCode=" + response.code());
        utils.log("LoggingInterceptor", "redirectUri=" + response.header("Location"));
        return response;
    }
}

最新更新