source: Dev/branches/play-2.0.1/documentation/manual/sandbox/Javahttp.md @ 322

Last change on this file since 322 was 322, checked in by hendrikvanantwerpen, 13 years ago

Added Play! framework and application with Jena dependency. Working on
the basic things now (login/register), after that start implementing
our data model.

File size: 1.8 KB
Line 
1# Making HTTP Requests
2
3Sometimes 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
5Any 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
11import play.libs.*;
12
13F.Promise<WS.Response> promise = WS.url("http://mysite.com").get();
14
15WS.Response res = promise.get();
16
17String body = res.getBody();
18
19int status = res.getStatus();
20
21String contentType = res.getHeader("Content-Type");
22
23org.w3c.dom.Document doc = res.asXml();
24
25org.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
36import play.libs.*;
37import com.ning.http.client.Realm;
38
39F.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");
44String body = jpromise.get().getBody();
45//and body should contain AnyContentAsUrlFormEncoded
46
47```
48
49For 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)
Note: See TracBrowser for help on using the repository browser.