如何在Okhttp中使用Socks5代理来启动http请求

时间:2016-10-13 01:57:13

标签: java okhttp3

如何在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? 任何一个例子?

谢谢!

2 个答案:

答案 0 :(得分:3)

我找到了一个解决方案:当创建一个OkHttpClient.Builder()时,设置一个新的socketFactory而不是set proxy,并在socketFactory createSocket中返回一个sock5代理。

答案 1 :(得分:0)

我认为这是最简单的工作解决方案。但是在我看来,它可能不是100%安全的。我从此代码from here中获取了此代码,并对其进行了修改,因为我的代理的RequestorType是SERVER。 实际上,java对于代理有一个奇怪的api,您应该通过系统env为代理设置auth(您可以从同一链接中看到它)

final int proxyPort = 1080; //your proxy port
final String proxyHost = "your proxy host";
final String username = "proxy username";
final String password = "proxy password";

InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);

Authenticator.setDefault(new Authenticator() {
  @Override
  protected PasswordAuthentication getPasswordAuthentication() {
    if (getRequestingHost().equalsIgnoreCase(proxyHost)) {
      if (proxyPort == getRequestingPort()) {
        return new PasswordAuthentication(username, password.toCharArray());
      }
    }
    return null;
  }
});


OkHttpClient client = new OkHttpClient.Builder()
        .proxy(proxy)
        .build();