如何在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());
如何避免UnknownHostException? 有什么例子吗?
谢谢!
最佳答案
我找到了一个解决方案:当创建OkHttpClient.Builder()时,设置一个新的socketFactory而不是设置代理,并在socketFactory createSocket中返回一个sock5代理。
关于java - 如何在Okhttp中使用Socks5代理来启动http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40011055/