In this tutorial, we will create a method that listens a POST request from a client and returns an appropriated message. We reuse class created in the previous tutorial. We also modify the client java class in the first tutorial to send a POST request.
package forthREST; import org.restlet.Application; import org.restlet.Restlet; import org.restlet.routing.Router; public class RouterApplication extends Application{ /** * Creates a root Restlet that will receive all incoming calls. */ @Override public synchronized Restlet createInboundRoot() { // Create a router Restlet that routes each call to a new respective instance of resource. Router router = new Router(getContext()); // Defines only three routes router.attach("/users", UserResource.class); router.attach("/users/{uid}", UserResource.class); router.attach("/users/{uid}/items", UserItemResource.class); return router; } }
@Post
public Representation acceptItem(Representation entity) {
Representation result = null;
// Parse the given representation and retrieve data
Form form = new Form(entity);
String uid = form.getFirstValue("uid");
String uname = form.getFirstValue("uname");
if(uid.equals("123")){ // Assume that user id 123 is existed
result = new StringRepresentation("User whose uid="+ uid +" is updated",
MediaType.TEXT_PLAIN);
}
else { // otherwise add user
result = new StringRepresentation("User " + uname + " is added",
MediaType.TEXT_PLAIN);
}
return result;
}
package client; import java.io.IOException; import org.restlet.data.Form; import org.restlet.representation.Representation; import org.restlet.resource.ClientResource; import org.restlet.resource.ResourceException; public class ClientCall { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // Create the client resource ClientResource resource = new ClientResource("http://localhost:8182/users"); Form form = new Form(); form.add("uid", "1234"); form.add("uname", "John"); // Write the response entity on the console try { resource.post(form).write(System.out); } catch (ResourceException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }