How to get OkHttp3 redirected URL?

11,385

Solution 1

The response object provides a chain of the requests and responses which were used to obtain it.

To obtain the final URL, call request() on the Response for the final Request which then provides the url() you desire.

You can follow the entire response chain by calling priorResponse() and looking at each Response's associated Request.

Solution 2

The OkHttp.Builder has NetworkInterceptor provided.Here is an example:

        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

Solution 3

You can use "Location" from response header (see topic https://stackoverflow.com/a/41539846/9843623). Example:

{
{
    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;
    }
}
Share:
11,385

Related videos on Youtube

Gatonito
Author by

Gatonito

Updated on June 27, 2022

Comments

  • Gatonito
    Gatonito almost 2 years

    Is there a way to get the final URL of a request? I know that I can disable redirections and to this myself, but is there a way to get the current URL I'm loading? Like, if I requested a.com and got redirected to b.com, is there a way to get the name of the url b.com?