I'm using the https://github.com/AsyncHttpClient/async-http-client to send an asynchronous POST request.
Example:
try {
CompletableFuture<org.asynchttpclient.Response> whenResponse = asyncHttpClient()
.preparePost("https://some-site.com/v1/subscription1")
.setHeader("Content-Type","application/json")
.setHeader("Accept", "application/json")
.setBody(getData())
.execute()
.toCompletableFuture()
.exceptionally(t -> {
// handle error
})
.thenApply(
response -> { return response; }
);
return whenResponse.join();
} catch (Exception e) {
// handle error
}
Is it possible to refactor this to send the same data/body to multiple URLs asynchronously?
Preferably outlining the most efficient way (can loops be avoided here)?
First of all, when using
asyncHttpClient()you should remember to close theAsyncHttpClientreturned by that method once you are done sending your requests. Alternatively, you could define anAsyncHttpClientinstance globally and reuse it for all your requests.Since you commented that CompletableFuture.allOf() does work for you, I assume that you're not interested in the results returned by the requests. If you are, your method could return a list of the individual
CompletableFutureinstances which you can safely inspect after callingjoin()on the instance created byallOf(). Thisjoincall would then have to be moved inside that method.Loops can clearly not be avoided unless you want to hardcode your URLs in which case you have to unroll the loop and create the array that is passed to
allOfby hand.Here is an example of how you could implement the solution: