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?
Asked
Active
Viewed 1.4k times
3 Answers
35
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
.

Jake Wharton
- 75,598
- 23
- 223
- 230
5
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());

Colin Chen
- 61
- 2
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;
}
}

user9843623
- 31
- 3