Restful webservices in java.
This week I’ve been experimenting with Jersey Which is an implementation of the JSR-311 specification of a java API for Restful Webservices.
One of the problems with developing restful webservices using java or c# is the tool support doesn’t really exist yet. So with SOAP you can easily expose any interface as a web service, and add web references in your IDE of choice & call a remote system as easily as if it were part of your local application. With a RESTful webservices it has tended to involve messing about with HTTP apis and manually parsing URLs & XML (at least in java & .net).
Anyhow, I’ve been quite impressed with the JSR-311 API, it is exceptionally easy to use. You can do something like the following:
@HttpMethod
@UriTemplate(”/foo”);
@ProduceMime(“application/x-myxml”)
public Foo getFoo() {
return new Foo();
}
Jersey will then do all the hard work so if you run/deploy the service you can go to http://localhost/foo and will be returned a shiny new Foo object converted to XML format courtesy of jaxb.
Consuming this on the client is also quite easy thanks to jaxb, and jax-ws. Consuming a method such as above could be as simple as the following (with a small wrapper around JAX-WS api).
RestClient client = new RestClient(“http://localhost”,Foo.class,Bar.class);
Foo foo = client.get(”/foo”);
Bar bar = client.get(”/bar”);
And have it make a request, unmarshal the XML back into a java object and give it to you.
HttpMethod can indicate the verb if it’s not obvious from the method name. e.g. @HttpMethod(“PUT”). Different methods at the same UriTemplate with different Mimetypes will be picked depending on the accepted mimes in the http headers. So you can display an html page when viewing in a browser, or plain XML to other systems, or images etc.
Accepting parameters is equally easy:
@HttpMethod
@UriTemplate(”/baz/{id}”)
public Baz getBaz(@UriParam(“id”) int id)
...
will automatically convert an id parameter on the URL to an integer for the method parameter.
Loading…
Add a comment
You are not allowed to comment on this entry as it has restricted commenting permissions.