有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

如何避免未知的后异常? 有什么例子吗

谢谢


共 (2) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

    我认为这是最简单的解决方法。但在我看来,它可能不是100%安全的。我从这个代码from here中获取了这段代码,并对其进行了修改,因为我的代理的RequestorType是SERVER。 实际上,java有一个奇怪的代理api,您应该通过system 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();