Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OkHttpClient limit number of connections?

Is it possible with OkHttpClient to limit the number of live connections? So if limit reached, no new connection is picked and established?

My app starts many connection at same time.

like image 634
János Avatar asked Feb 17 '17 13:02

János


People also ask

What is OkHttp connection pool?

What is OkHttp? OkHttp is an HTTP client from Square for Java and Android applications. It's designed to load resources faster and save bandwidth. OkHttp is widely used in open-source projects and is the backbone of libraries like Retrofit, Picasso, and many others.

Is OkHttp blocked?

OkHttp Overview At a high level, the client is designed for both blocking synchronous calls and nonblocking asynchronous calls. OkHttp supports Android 2.3 and above.


1 Answers

The number of connections is configurable in the Dispatcher, not in the ConnectionPool that only allows to configure the max idle connections and the keep alive functionality.

The dispatcher allows to configure the number of connections by hosts and the max number of connections, defaults are 5 per hosts and 64 in total. This can seems low for HTTP/1 but are OK if you use HTTP/2 as multiple requests can be send to one connection.

To configure the dispatcher, follow these steps :

Dispatcher dispatcher = new Dispatcher();
dispatcher.setMaxRequests(100);
dispatcher.setMaxRequestsPerHost(10);
OkHttpClient client = new OkHttpClient.Builder()
    .dispatcher(dispatcher)
    .build();
like image 152
loicmathieu Avatar answered Oct 21 '22 08:10

loicmathieu