Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a different number of port using Square's okHttp?

Tags:

android

okhttp

I'm trying to connect okHttp with a web service but with different port, for example, 10000. My idea to stub the responses with a proxy during the unit tests. Neverthless, there is not enough documentation to make it with this library. As a matter of fact, my implementation is:

OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(TIMEOUT_MS, TimeUnit.MILLISECONDS);

For example, with other libraries such as loopj, this feature is possible:

httpClient.setProxy("localhost", 10000);

I'm using this version: com.squareup.okhttp:okhttp:2.5.0

like image 611
Jesús Castro Avatar asked Oct 12 '15 21:10

Jesús Castro


People also ask

Should OkHttp client be a singleton?

OkHttp performs best when you create a single OkHttpClient instance and reuse it for all of your HTTP calls. This is because each client holds its own connection pool and thread pools. Reusing connections and threads reduces latency and saves memory.

How do I turn off OkHttpClient connection?

close() will release all resources held by the response. The connection pool will keep the connection open, but that'll get closed automatically after a timeout if it goes unused. You can also call response. close() which, according to the documentation, is equivalent to response.

How do I create an OkHttpClient?

OkHttpClient client = new OkHttpClient(); Request getRequest = new Request. Builder() . url("https://mytodoserver.com/todolist") . build(); client.

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

I'm trying to connect okHttp with a web service but with different port, for example, 10000

Put the port in the URL that you supply to Request.Builder:

Request request = new Request.Builder()
    .url("http://publicobject.com:10000/helloworld.txt")
    .build();

My idea to stub the responses with a proxy during the unit tests.

Use a different URL for the tests than you do in production.

like image 84
CommonsWare Avatar answered Sep 29 '22 07:09

CommonsWare