java如何在Okhttp中使用Socks5代理来启动http请求
如何在Okhttp中使用Socks5代理来启动http请求
我的代码:
Proxy proxy = new Proxy(Proxy.Type.SOCKS, InetSocketAddress.createUnresolved(
"socks5host", 80));
OkHttpClient client = new OkHttpClient.Builder()
.proxy(proxy).authenticator(new Authenticator() {
@Override
public Request authenticate(Route route, Response response) throws IOException {
if (HttpUtils.responseCount(response) >= 3) {
return null;
}
String credential = Credentials.basic("user", "psw");
if (credential.equals(response.request().header("Authorization"))) {
return null; // If we already failed with these credentials, don't retry.
}
return response.request().newBuilder().header("Authorization", credential).build();
}
}).build();
Request request = new Request.Builder().url("http://google.com").get().build();
Response response = client.newCall(request).execute(); <--- **Here, always throw java.net.UnknownHostException: Host is unresolved: google.com**
System.out.println(response.body().string());
如何避免未知的后异常? 有什么例子吗
谢谢
# 1 楼答案
我找到了一个解决方案:创建OkHttpClient时。Builder(),设置一个新的socketFactory,而不是设置代理,并在socketFactory createSocket中返回一个Socket5代理
# 2 楼答案
我认为这是最简单的解决方法。但在我看来,它可能不是100%安全的。我从这个代码from here中获取了这段代码,并对其进行了修改,因为我的代理的RequestorType是SERVER。 实际上,java有一个奇怪的代理api,您应该通过system env为代理设置auth(您可以从同一个链接看到)