OkHttp 代理设置 [英] OkHttp proxy settings

查看:154
本文介绍了OkHttp 代理设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须设置一个代理才能使用 POST、proxyHost 和 proxyPort 发送 JSON.

I have to setup a proxy to send a JSON using POST, using proxyHost and 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 时,它指出了一个错误:

When i try to use the proxyTest that I've saw on some answers here it points an error:

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

The method proxy() in the type OkHttpClient is not applicable for the arguments (Proxy)

我使用的是 OKHTTP 3.3.1(okhttp3)

Iam using the OKHTTP 3.3.1(okhttp3)

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

My question is, what should I do? I did some tests like this:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.proxy(proxyTest);
client.setProxy(proxyTest)
OkHttp客户端客户端 = builder.build();

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

但到目前为止没有任何效果.

But nothing works so far.

感谢您的时间!

推荐答案

找到解决方案:

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

如果我们使用构建器输入代理,它会像魅力一样工作=D

If we use the builder to input the proxy, it will work like a charm =D

这篇关于OkHttp 代理设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆