Arun Gupta wrote:
> This may be a noob question :)
>
> For any RESTful web service, what is the recommended (different)
> way(s) to parse the response ? - XPath, JSON APIs, JAXP, JAXB, any
> other ?
>
> Is there anyway I can use JAXB to operate on the returned XML fragment
> ? I'd like to write a simple Java client that invokes a RESTful
> endpoint and process it without "much effort" :)
>
> Thanks,
> -Arun
If your client is Java, you ***really*** want to be using jersey-client,
where you can benefit from the same sort of provider infrastructure that
is used on the server. Assume you have a Customer class that is
annotated with JAXB annotations (so that Jersey will automatically find
the right MessageBodyReader for you). Next, assume you want to call a
method that returns a <customer> element (which will get mapped to your
Customer bean class). You could end up doing something like this:
public class MyClient {
public MyClient(String uri) {
ClientConfig config = new DefaultClientConfig();
client = Client.create(config);
service = client.resource(uri); // URI of web service endpoint
}
private Client client;
private WebResource service;
public Customer findCustomer(String id) {
try {
return
service.path("customers").path(id).accept("text/xml").get(Customer.class);
} catch (UniformInterfaceException e) {
... deal with exception for HTTP error status codes ...
}
}
}
If the server is also Jersey and Java based, a pattern I have found
really useful is to separate the JAXB-annotated data model classes into
a separate jar file (as a separate NB project or whatever), and use the
same JAR file in both the client and the server applications.
There are several samples in the Jersey distribution that use
jersey-client, and nearly all of the unit tests for server-side
functionality do so as well.
Craig