Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttp proxy settings

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

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

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

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)
OkHttpClient client = builder.build();

But nothing works so far.

Thanks for your time!

like image 829
Matheus Bica Avatar asked Jun 16 '16 18:06

Matheus Bica


People also ask

How do I add a proxy to OkHttp?

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

What is OkHttp client?

OkHttp is an efficient HTTP & HTTP/2 client for Android and Java applications. It comes with advanced features, such as connection pooling (if HTTP/2 isn't available), transparent GZIP compression, and response caching, to avoid the network completely for repeated requests.


1 Answers

Found the solution:

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

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

like image 133
Matheus Bica Avatar answered Sep 22 '22 00:09

Matheus Bica