前言
刚开始google okhttp如何设置相关资料时,这篇文章
https://stackoverflow.com/questions/35554380/okhttpclient-proxy-authentication-how-to
刚开始测试了几个https的站点,发现没问题。今天来公司访问几个http的站点发现显示状态码407 并提示 proxy authentication required,刚开始以为是squid配置的原因,google了一上午,查看squid配置详解,常识配置了相关的参数,关闭代理服务器防火墙发现都不行。后续思考,有可能不是squid配置的问题,于是把目光转移到了okhttp的认证配置上,google了许久发现在okhttp的GitHub上发现有个[Bug report] Proxy authenticate over http. #2414 完美的解决了该问题。
完整访问http/https代码
String host = "ip";//代理ip
int port = 80;//ip端口
String user = "user";//squid用户名
String password = "password";//squid密码
Authenticator proxyAuthenticator = new Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(user, password);
return response.request().newBuilder()
.header("Proxy-Authorization", credential)
.build();
}
};
OkHttpClient client = new OkHttpClient.Builder()
.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1, Protocol.SPDY_3))
.connectTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)))
.proxyAuthenticator(proxyAuthenticator)//这是重点
.authenticator(proxyAuthenticator)//这是重点
.build();
本文由 SAn 创作,采用 知识共享署名4.0 国际许可协议进行许可
本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名
最后编辑时间为:
2020/05/14 21:53