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

问题描述

我必须设置代理以使用ProxyHost和proxyPort通过POST发送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:

我使用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:

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

But nothing works so far.

感谢您的时间!

推荐答案

找到了解决方案:

 //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一样工作

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

最诚挚的问候!

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

07-30 07:35