【发布时间】:2019-09-13 21:15:21
【问题描述】:
我需要通过需要身份验证的代理发出请求。
public class WebClient {
private final OkHttpClient httpClient;
private static WebClient webClient;
private WebClient() {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (Configurator.getInstance().useProxy()) {
builder.proxySelector(new CustomProxySelector());
builder.authenticator((Route route, Response response) -> {
String credential = Credentials.basic("MYUSER", "MYPSW");
return response.request().newBuilder().header("Authorization", credential).build();
});
} else
builder.proxy(Proxy.NO_PROXY);
httpClient = builder
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
}
}
但是使用调试器时,我看到验证器方法永远不会被调用,并且我收到 407 作为任何请求的响应。
但是,当我将 HttpURLConnection 与 Authenticator.setDefault 一起使用时,它工作得很好,我可以使用我的代理身份验证:
public boolean hasInternetConnection() throws IOException {
Request httpRequest = new Request.Builder().url("http://www.google.com/").build();
// This fails with 407
Response httpResponse = httpClient.newCall(httpRequest).execute();
java.net.Authenticator authenticator = new java.net.Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("MYUSER", "MYPSW".toCharArray()));
}
};
java.net.Authenticator.setDefault(authenticator);
URL obj = new URL("http://www.google.com/");
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
// This works with 200
int responseCode = con.getResponseCode();
return false;
}
所以我认为问题是:为什么没有调用 OkHttpClient.Builder.authenticator 方法?
【问题讨论】:
-
最简单的答案是:因为
Configurator.getInstance().useProxy()返回false。 -
它返回 true 因为我可以看到 ProxySelector 处于活动状态。
-
很公平。 407 意味着代理授权质询。是不是您想改用
proxyAuthenticator()(这意味着您想设置一个代理授权标头来响应挑战)?喜欢这里:stackoverflow.com/a/35567936/424903 -
是的。问题之一是您指出的错误方法。现在我正在测试其他东西来回答这个问题。
标签: java http proxy okhttp okhttp3