2

How can I use Socks5 proxy in Okhttp to start http request ?

My code:

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());

How to avoid UnknownHostException? Any example ?

Thanks!

zzz zzz
  • 89
  • 1
  • 5

2 Answers2

4

I found a solution: When create a OkHttpClient.Builder(), set a new socketFactory instead of set proxy, and return a sock5 proxy inside socketFactory createSocket.

zzz zzz
  • 89
  • 1
  • 5
1

I think it's the easiest working soulution. But it seems to me that it can be not 100% safe. I took this code from this code from here and modified it because my proxy's RequestorType is SERVER. Actually, java has a strange api for proxies, you should to set auth for proxy through system env ( you can see it from the same link)

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();
Eugene Kortov
  • 445
  • 6
  • 17