Play Framework – Calling Web Services

Now and then we might want to call other HTTP administrations from inside a Play application. Play backs this by means of its WS library, which gives an approach to make offbeat HTTP calls.

There are two paramount parts to utilizing the WS API: making a solicitation, and handling the reaction. We’ll examine how to make both GET and POST HTTP asks for initially, and afterward demonstrate to process the reaction from WS. At long last, we’ll talk about some regular utilization cases.

Making a Request

To utilize WS, first add javaws to your build.sbt document:

librarydependencies ++= Seq( javaws )

At that point, import the accompanying:

import play.libs.ws.*;
import play.libs.f.function;
import play.libs.f.promise;

To manufacture a HTTP demand, you begin with Ws.url () to specify.

requestholder holder = Ws.url("xyz.com");

Return a request holder that you can use to specify different HTTP alternatives, for example, setting headers. You can fasten assembles to build complex appeals.

Wsrequestholder complexholder = holder.setheader("headerkey", "headervalue").settimeout(1000)
.setqueryparameter("paramkey", "paramvalue")


Demand with verification
You can end by calling a technique relating to the HTTP strategy you need to utilize. This finishes the chain, and uses all the choices characterized on the assembled ask for in the Wsrequestholder. Returns an obligation<wsresponse> where the Wsresponse contains the data came back from the server.

If you have to utilize HTTP verification, specify it in the manufacturer, utilizing a username, secret key, and a Wsauthscheme.

WS.url(url).setAuth("user", "password", WSAuthScheme.BASIC).get();

Demand with take after redirects

If a HTTP call brings about a 302 or a 301 redirect, you can consequently take after the redirect without needing to make an alternate call.

ws.url(url).setfollowredirects(true).get();

Demand with question parameters

You can specify question parameters for an appeal.

ws.url(url).setqueryparameter("paramkey", "paramvalue");

Request processing with extra headers

ws.url(url).setheader("headerkey", "headervalue").get();

Case in point, if you are sending plain content in a specific arrangement, you may need to characterize the substance sort expressly.

ws.url(url).setheader("content-Type", "application/json").post(jsonstring);

If you wish to specify a solicitation timeout, you can utilize setTimeout to set a worth in milliseconds.

Request processing with time out

Ws.url(url).setTimeout(1000).get();

To post URL-structure encoded data you can set the correct header and arranged data.

Submitting Structure data

ws.url(url).setcontenttype("application/x-www-structure urlencoded").post("key1=value1&key2=value2");

The most straightforward approach to post JSON data is to utilize the JSON library.

Submitting JSON data

import com.fasterxml.jackson.databind.jsonnode;
import play.libs.json;
Jsonnode json = Json.newobject().put("K1", "val1") ;
.put("k2", "val2");
ws.url(url).post(json)

Preparing the Response

Working with the WS response is carried out by mapping inside the Promise.

Preparing a response as JSON

You can prepare the response as a Json node by response.asjson()

Promise<jsonnode> jsonpromise = Ws.url(url).get().map(new Function<wsresponse, Jsonnode>() {
public JsonNode apply(wsresponse reaction) {
Jsonnode json = response.asjson();
return json;
} } );

So also, you can transform the response as XML

Preparing a response as XML

Promise<document> 
documentpromise = Ws.url(url).get().map(new Function<wsresponse, Document>() {
public Document apply(wsresponse reaction) {
Archive xml = response.asxml();
return xml;

}});

When you are downloading a vast record or archive, WS permits you to get the reaction body as an Inputstream so you can prepare the data without stacking the whole substance into memory immediately.

Preparing responses

Java 8

final Promise<File> filePromise = WS.url(url).get().map(
        new Function<WSResponse, File>() {
            public File apply(WSResponse response) throws Throwable {

                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = response.getBodyAsStream();

                    // write the inputStream to a File
                    final File file = new File("/tmp/response.txt");
                    outputStream = new FileOutputStream(file);

                    int read = 0;
                    byte[] buffer = new byte[1024];

                    while ((read = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, read);
                    }

                    return file;
                } catch (IOException e) {
                    throw e;
                } finally {
                    if (inputStream != null) {inputStream.close();}
                    if (outputStream != null) {outputStream.close();}
                }

            }
        }
);