Cristian Boariu
Cristian Boariu

Reputation: 9621

How to make multiple http requests in play 2?

I want to make multiple web requests for an external api using play 2. Each web requests will be different by the page parameter. My code is:

static WSRequestHolder urlPaging = WS
        .url("http://my_api")
        .setQueryParameter("apiKey", "api_key")
        .setQueryParameter("pageSize", "5")
        .setQueryParameter("format", "json");

public static Result insertProducts() {
    int totalPages = 83;
    Logger.info("total pages: " + totalPages);
    for (int currentPage = 1; currentPage < totalPages; currentPage++) {
        Logger.info("--current page:" + currentPage);
        result(currentPage);
    }
    return ok();
}

public static AsyncResult result(int currentPage) {
    return async(urlPaging
            .setQueryParameter("page", String.valueOf(currentPage)).get()
            .map(new Function<WS.Response, Result>() {
                public Result apply(WS.Response response) {
                    insertProductsFromPage(response);
                    return ok();
                }
            }));
}

It works for page 1, but gives me internall error for page 2 so I suspect I am not building result async request method properly. Please note that I don't need this really async because I am running this from admin and I can wait there until all these requests are parsed but I have not found a sync way in play 2 for this. Can you please let me know what I am doing wrong?

Upvotes: 4

Views: 1728

Answers (1)

ndeverge
ndeverge

Reputation: 21564

If you want to make external WS calls synchronously, just use the get() method of the promise.

For example:

Promise<WS.Response> promise = urlPaging.setQueryParameter("page", String.valueOf(currentPage)).get();
WS.Response response = promise.get(); // wait for the result of the promise.

Upvotes: 5

Related Questions