如何让 OkHttp3 重定向 URL?
How to get OkHttp3 redirected URL?
有没有办法获取请求的最终 URL?我知道我可以自己禁用重定向,但是有没有办法获取我正在加载的当前 URL?比如,如果我请求 a.com 并被重定向到 b.com,有没有办法获取 url b.com 的名称?
响应对象提供用于获取它的请求和响应链。
要获得最终的 URL,请致电 request()
on the Response
for the final Request
which then provides the url()
您想要的。
您可以通过调用 priorResponse()
并查看每个 Response
的关联 Request
.
来跟踪整个响应链
OkHttp.Builder有NetworkInterceptor provided.Here就是一个例子:
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());
您可以使用响应 header 中的 "Location"(参见主题 https://whosebug.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;
}
}
有没有办法获取请求的最终 URL?我知道我可以自己禁用重定向,但是有没有办法获取我正在加载的当前 URL?比如,如果我请求 a.com 并被重定向到 b.com,有没有办法获取 url b.com 的名称?
响应对象提供用于获取它的请求和响应链。
要获得最终的 URL,请致电 request()
on the Response
for the final Request
which then provides the url()
您想要的。
您可以通过调用 priorResponse()
并查看每个 Response
的关联 Request
.
OkHttp.Builder有NetworkInterceptor provided.Here就是一个例子:
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());
您可以使用响应 header 中的 "Location"(参见主题 https://whosebug.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;
}
}