使用OkHTTP
我有两种配置重定向的方法 -
followRedirects(boolean followRedirects)
- >配置是否允许重定向。followSslRedirects(boolean followProtocolRedirects)
- >配置是否允许HTTP
- > HTTPS
和HTTPS
- > HTTP
重定向。虽然我希望实现的是允许HTTP
- > HTTPS
重定向同时阻止HTTPS
- > HTTP
重定向。我能想到的唯一方法是添加一个OkHTTP
拦截器,如下面的代码所示,以检查请求和响应URL协议。虽然我不确定它是否是实现此目的的最佳/最正确的方法,因为我们仍然在执行chain.proceed(request)
时调用重定向的URL。任何人都可以指出我在这里采取更好的方法。感谢。
new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (!isValidRedirect(request.url(), response.request().url())) {
throw new IOException("Invalid redirect from secure server to insecure server");
}
return response;
}
})
.build();
private static boolean isValidRedirect(HttpUrl url, HttpUrl newUrl) {
//unless it's https, don't worry about it
if (!url.url().getProtocol().equals("https")) {
return true;
}
// If https, verify that we're on the same server.
// Not being so means we got redirected from a secure link to a
// different link, which isn't acceptable.
return url.url().getHost().equals(newUrl.url().getHost());
}