Creating queries is straightforward. First you specify the url. There are various ways to add content types, request parameters, timeouts, etc. In request. Then you select the type of request and, possibly, add some content to send. Examples:
WSRequestHolder request = WS.url("http://example.com"); request.setQueryParameter("page", "1"); Promise<Response> promise = request.get();
Promise<Response> promise = WS.url("http://example.com").post(content);
The tricky part is to send it and use the response of the request. I assume that you have a controller that should return the Result user to the user based on the response of the web service. The result is usually a displayed template or maybe just a status code.
Playback avoids blocking using Futures and Promises . The async controller accepts a Promise<Result> and returns a result (future value) at some point later. An easy-to-use promise is the get and post methods shown above. You do not need to worry about their implementation, you just need to know what they promised to provide Response after the request is completed.
Note the problem here: when creating a query using WS.url("...").get() it will give you a Promise<Response> , although async takes a Promise<Result> . Here you must fulfill another promise yourself, which converts the answer to the result using the map method. If you follow the Play documentation, this will be a bit confusing because Java has no closures (though) and everything needs to be wrapped in a class. However, you do not need to use anonymous classes inside the method call. If you prefer cleaner code, you can also do it like this:
return async( request .get()
The resultFromResponse object may look like this. This is actually just like a cumbersome definition of some kind of callback method that takes a Response as soon as an argument and returns a Result .
Function<Response, List<T>> resultFromResponse = new Function<Response , Result >() { @Override public Result apply(Response response) {
As @itsjeyd pointed out in the comments when calling web services in Play 2.2.x , you no longer end the call in async . You just return the Promise<Result> :
public static Promise<Result> index() { return request.get().map(resultFromResponse); }