OkHttp代理设置

时间:2016-06-16 18:34:16

标签: java json post proxy okhttp3

我必须使用proxyHost和proxyPort设置代理以使用POST发送JSON。

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
  Proxy proxyTest = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("proxy", proxyPort));

  OkHttpClient client = new OkHttpClient()
  .proxy(proxyTest)
  .build();
  //OkHttpClient.Builder builder = new OkHttpClient.Builder();
  //builder.proxy(proxySAP);
  //client.setProxy(proxySAP)
  //OkHttpClient client = builder.build();;

  String post(String url, String json) throws IOException {

    RequestBody body = RequestBody.create(JSON, json);
    Request request = new Request.Builder()
        .url(url)
        .post(body)
        .build();
    try (Response response = client.newCall(request).execute()) {
      return response.body().string();
    }
  }

当我尝试使用我在一些答案上看到的proxyTest时,它指出了一个错误:

  

OkHttpClient类型中的方法proxy()不适用于   参数(代理)

我使用OKHTTP 3.3.1(okhttp3)

我的问题是,我该怎么办?我做了一些像这样的测试:

  

OkHttpClient.Builder builder = new OkHttpClient.Builder();
  builder.proxy(proxyTest);
  client.setProxy(proxyTest)
  OkHttpClient   client = builder.build();

但到目前为止没有任何作用。

谢谢你的时间!

3 个答案:

答案 0 :(得分:18)

找到解决方案:

 //OkHttpClient client = new OkHttpClient();

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

  //builder.proxy(proxyTest);
  //client.setProxy(proxyTest)
  //OkHttpClient client = builder.build();;

如果我们使用构建器输入代理,它将像charm = D

一样工作

最诚挚的问候!

答案 1 :(得分:5)

okhttp版本:3.11.0。 SOCKS代理示例

String hostname = "localhost"/*127.0.0.1*/;
int port = 1080;
Proxy proxy = new Proxy(Proxy.Type.SOCKS,
        new InetSocketAddress(hostname, port));

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

答案 2 :(得分:1)

SOCKS5身份验证示例

我认为这是最简单的工作解决方案。但是在我看来,它可能不是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();