1 | # Making HTTP Requests |
---|
2 | |
---|
3 | Sometimes we would like to call other HTTP services from within a play application. Play supports this task via its ```play.libs.WS``` library which provides a way to make asynchronous HTTP calls. |
---|
4 | |
---|
5 | Any calls made by ```play.libs.WS``` should return a ``` play.libs.F.Promise<play.libs.WS.Response>``` which we can later handle with play's asynchronous mechanisms. |
---|
6 | |
---|
7 | # A short introduction |
---|
8 | |
---|
9 | ## Hello Get |
---|
10 | ```java |
---|
11 | import play.libs.*; |
---|
12 | |
---|
13 | F.Promise<WS.Response> promise = WS.url("http://mysite.com").get(); |
---|
14 | |
---|
15 | WS.Response res = promise.get(); |
---|
16 | |
---|
17 | String body = res.getBody(); |
---|
18 | |
---|
19 | int status = res.getStatus(); |
---|
20 | |
---|
21 | String contentType = res.getHeader("Content-Type"); |
---|
22 | |
---|
23 | org.w3c.dom.Document doc = res.asXml(); |
---|
24 | |
---|
25 | org.codehaus.jackson.JsonNode json = res.asJson(); |
---|
26 | |
---|
27 | ``` |
---|
28 | |
---|
29 | _Note: in this example we used ```play.libs.F.Promise#get``` to retrieve the result of the promise in a blocking fashion, however, since this is an async call, one might want to avoid blocking by handling the promise via ```play.libs.F.Promise#onRedeem``` callback or ```play.libs.F.Promise#map``` or even ```play.libs.F.Promise#flatMap```._ |
---|
30 | |
---|
31 | _[Please consult the javadoc for more information](https://github.com/playframework/Play20/blob/master/framework/src/play/src/main/java/play/libs/F.java)_ |
---|
32 | |
---|
33 | |
---|
34 | ## Hello Post |
---|
35 | ```java |
---|
36 | import play.libs.*; |
---|
37 | import com.ning.http.client.Realm; |
---|
38 | |
---|
39 | F.Promise<WS.Response> jpromise = WS.url("http://mysite.com/post") |
---|
40 | .setHeader("Content-Type","application/x-www-form-urlencoded") |
---|
41 | .setAuth("peter","superSecret",Realm.AuthScheme.SPNEGO) |
---|
42 | .setQueryParam("myqparam","1") |
---|
43 | .post("param1=foo"); |
---|
44 | String body = jpromise.get().getBody(); |
---|
45 | //and body should contain AnyContentAsUrlFormEncoded |
---|
46 | |
---|
47 | ``` |
---|
48 | |
---|
49 | For more information please see the api doc [here](https://github.com/playframework/Play20/blob/master/framework/src/play/src/main/java/play/libs/WS.java) |
---|