Sunday, May 3, 2015

Invoking web services using Restlet

Restslet is a good framework to invoke rest based web services. Let's see through a simple program how to write a client to invoke Rest based webservices.

First  maven dependency

<repositories>
<repository>
<id>maven-restlet</id>
<name>Restlet repository</name>
<url>http://maven.restlet.com</url>
</repository>
</repositories>
<properties>
<restlet-version>2.3.1</restlet-version>
</properties>



<dependencies>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet</artifactId>
<version>${restlet-version}</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.jackson</artifactId>
<version>${restlet-version}</version>
</dependency>
<dependency>
<groupId>org.restlet.jse</groupId>
<artifactId>org.restlet.ext.json</artifactId>
<version>${restlet-version}</version>
</dependency>
</dependencies>

and the program

String restUrl = "<URL of web service>";

// Let's say the json request is
// {"key1":"value1", "key2":"value2",
// "arrayKey1" : {"value3","value4"},
// "key5":"value5"
// }

JSONStringer jsRequest = new JSONStringer();
try {
jsRequest.object();
jsRequest.key("key1").value("value1");
jsRequest.key("key2").value("value2");
jsRequest.key("arrayKey1").array();
jsRequest.value("value3");
jsRequest.value("value4");
jsRequest.endArray();
jsRequest.key("key5").value("value5");
jsRequest.endObject();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(jsRequest.toString());

ClientResource clientResource = new ClientResource(restUrl);

Representation rep = new JsonRepresentation(jsRequest);
rep.setMediaType(MediaType.APPLICATION_JSON);
Representation reply = clientResource.post(rep);
String replyText = reply.getText();
System.out.println("Reply Text:" + replyText);
System.out.println("Reply Media Type:" + reply.getMediaType());

// Let's say the reply is
// {"message":"This is the message"}
String id = null;
if (reply.getMediaType().equals(new MediaType("application/json"))) {
JSONObject jsObj = new JSONObject(replyText);
String message = jsObj.getString("message");
System.out.println("Message :" + message);
}
reply.release();

No comments:

Post a Comment