Java Reference
In-Depth Information
private static void getUser(int id) {
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(SERVICE_URL + id);
get.setRequestHeader("Accept", "text/xml");
try {
int httpStatus = client.executeMethod(get);
if (HttpStatus.SC_OK == httpStatus) {
String xmlResponse = get.getResponseBodyAsString();
System.out.println("Xml User Response: " +
xmlResponse);
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//clean up
get.releaseConnection();
}
}
}
The client creates a new instance of the POST method for interacting with the service. It then
sends that XML to the service, which will select the postUser method and invoke the JAXB
framework to translate the XML into a User object and then save it to the database.
In the next method invocation, you use a GET method to look up the user you just created.
Running the client produces the following output on the console:
Creating new user.
Xml User Response:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user><id>777</id><username>eben</username></user>
All done.
Here you do not return to the client any additional state transition possibilities. You just return
the entity itself, and that's the end of the road. But it does illustrate how to use POST and
GET together, and one way of creating objects on the server, as well as some of the supporting
plumbing in JAX-RS, such as UriBuilder and ResponseBuilder .
Search WWH ::




Custom Search