确定Http代理设置

2022-09-01 10:39:28

我必须设置一个代理来使用POST发送JSON,使用proxyHost和proxyPort。

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() 不适用于参数 (Proxy)

Iam 使用 OKHTTP 3.3.1(okhttp3)

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

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

但到目前为止,一切都不起作用。

感谢您抽出宝贵时间接受采访!


答案 1

找到解决方案:

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

如果我们使用生成器输入代理,它将像charm = D一样工作


答案 2

okhttp version:.袜子代理示例3.11.0

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