【发布时间】:2018-04-25 18:15:21
【问题描述】:
GitHub 上有类似问题:https://github.com/square/okhttp/issues/2900
我正在尝试使用代码发出请求:
final Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxyhost", 8001));
final Response response = new OkHttpClient.Builder()
.proxy(proxy)
.proxyAuthenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic("proxyuser", "proxypass");
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
})
.build()
.newCall(new Request.Builder()
.get()
.url("https://www.google.com/")
.build())
.execute();
但我得到了错误:407 Proxy Authentication Required
顺便说一句,当我在我的电脑上设置代理时,打开 Chrome 并转到谷歌,会弹出一个窗口,我应该在其中输入登录名和密码。如果我点击取消 - 同一页面出现文本
407 需要代理身份验证。访问请求的资源 管理员不允许或您需要有效的用户名/密码才能使用 这个资源
所以我的问题是如何在 OkHttp 中使用代理?了解使用代理的其他方式或库会很有用
【问题讨论】:
-
看起来您的配置正确。您能否确认正在调用身份验证器?
-
@JesseWilson 是的,绝对。在“public Request authenticate(Route route, Response response)”中,响应代码为 407,执行代码时抛出 java.net.ProtocolException: Unexpected status line
-
明白了。这是一个解析错误。您的代理正在返回 OkHttp 无法处理的内容。如果你能诊断出来,那会有所帮助。