I am trying to access another service by Http to fetch data using HttpClient. The uri should look like endpoint:80/.../itemId.
I am wondering if there is a way to make a batch call to specify a set of itemIds? I did find someone suggests to .setHeader(HttpHeaders.CONNECTION, "keep-alive") when creating request. Via doing this, how could I release the client after getting all data?
Also, seems like this method still need to get one response then send another request? Is this possible to do it as async, and how? BTW, seems like I could not use AsyncHttpClient in this case for some reason.
Since I am barely know nothing about HttpClient, the question may look dumb. Really hope someone could help me solve the problem.
API support on the server
There is a small chance that the API supports requesting multiple IDs at a time (e.g. using a URL of the form
http://endpoint:80/.../itemId1,itemId2,itemId3
). Check the API documentation to see if this is available, because if so that would be the best solution.Persistent Connections
It looks like Apache HttpClient uses persistent ("keep alive") connections by default (see the Connection Management tutorial linked in @kichik's comment). The logging facilities could help to verify that connections are reused for several requests.
To release the client, use the
close()
method. From 2.3.4. Connection manager shutdown:Persistent connections eliminate the overhead of establishing new connections, but as you've noted the client will still wait for a response before sending the next request.
Multithreading and Connection Pooling
You can make your program multithreaded and use a PoolingHttpClientConnectionManager to control the number of connections made to the server. Here is an example based on 2.3.3. Pooling connection manager and 2.4. Multithreaded request execution:
Multithreading will help saturate the link (keep as much data flowing as possible) because while one thread is sending a request, other threads can be receiving responses and utilizing the downlink.
Pipelining
HTTP/1.1 supports pipelining, which sends multiple requests on a single connection without waiting for the responses. The Asynchronous I/O based on NIO tutorial has an example in section 3.10. Pipelined request execution:
There is a full version of this example in the HttpCore Examples ("Pipelined HTTP GET requests").
Older web servers may be unable to handle pipelined requests correctly.