Home How to send multiple asynchronous requests in parallel using Unirest
Reply: 0

How to send multiple asynchronous requests in parallel using Unirest

user5905
1#
user5905 Published in September 21, 2018, 8:04 am

While using Unirest, the program doesn't exit until we manually shutdown every thread by invoking Unirest.shutdown(). If I had to make just one request, it's easy:

private static void asyncRequest (String link) {
    try {
        Future <HttpResponse <JsonNode>> request = Unirest.head(link).asJsonAsync(
                new Callback<JsonNode>() {
                    @Override
                    public void completed(HttpResponse<JsonNode> httpResponse) {
                        print(httpResponse.getHeaders());
                        try {
                            Unirest.shutdown();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void failed(UnirestException e) {
                        print(e.getMessage());
                    }

                    @Override
                    public void cancelled() {
                        print("Request cancelled");
                    }
                }
        );

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws Exception {
   asyncRequest("https://entrepreneur.com");
}

But I have to make multiple HTTP request in parallel (subsequent requests are meant not to wait for previous requests to complete). In the code above, I have to execute the code inside asyncRequest more than once with different links. The problem is I can't decide when to invoke Unirest.shutdown() so that the program exits as soon as the last request receives response. If I call Unirest.shutdown() after all the calls to asyncRequest in main, some or all the requests might get interrupted. If I call it inside completed (and other overridden methods), only the first request is made and others are interrupted. How can I solve this?

share|improve this question

1 Answer 1

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.396952 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO