TOTD #58: Jersey and GlassFish - how to process POST requests ?
Posted by arungupta on December 1, 2008 at 9:30 AM EST
Lets extend the Jersey endpoint (TOTD# 56) and client (TOTD# 57) such that it can accept a POST request and then invoke it.
- Add a new method to "MyResource.java" from TOTD#
56 as:
@POST
@Consumes("application/json")
@Produces("application/json")
public Greeting postIt(Greeting greeting) {
System.out.println("In POST: " + greeting.greeting);
return greeting;
}
The first line indicates that the Java method will process HTTP POST requests. The second and third line shows that the method consumes and produces JSON data format.
- Add a new method to "AppTest.java" from TOTD#
57 as:
public void testPost() {
Greeting result = createResource().
type("application/json").
post(Greeting.class, new Greeting("yo!"));
assertTrue(result.greeting.equals("yo!"));
}
The main difference from the "testApp()" method is specifying the MIME type of the generated outbound request as "application/json".
- Running the test as "mvn test" shows the following output:
Running org.glassfish.samples.AppTest
1 * Out-bound request
1 > GET http://localhost:8080/helloworld-webapp/webresources/myresource
1 >
1 < 200
1 < X-Powered-By: Servlet/2.5
1 < Transfer-Encoding: chunked
1 < Content-Type: text/plain
1 < Server: GlassFish/v3
1 < Date: Tue, 25 Nov 2008 20:19:34 GMT
1 <
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><greeting><greeting>Hi there!</greeting></greeting>
1 * In-bound response
1 * Out-bound request
1 > POST http://localhost:8080/helloworld-webapp/webresources/myresource
1 > Content-Type: application/json
1 >
{"greeting":"yo!"}
1 < 200
1 < X-Powered-By: Servlet/2.5
1 < Transfer-Encoding: chunked
1 < Content-Type: application/json
1 < Server: GlassFish/v3
1 < Date: Tue, 25 Nov 2008 20:19:34 GMT
1 <
{"greeting":"yo!"}
1 * In-bound response
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.191 sec
The output shows request/response messages when both the tests are run together. Here are some highlights: - "GET" and "POST" methods are clearly highlighted.
- The two "Content-Type" headers with value "text/plain" and "application/json" are output from two tests. The output from POST method has two Content-Type headers, one for outbound request and another one for inbound response.
- The body content of POST method is using JSON format.
How are you using Jersey ?
Send all your questions to users@jersey.dev.java.net.
Please leave suggestions on other TOTD (Tip Of The Day) that you'd like to see. An archive of all the tips is available here.
Technorati: totd glassfish v3 embeddable jersey jsr311 rest json webservices
Related Topics >>
Blog Links >>
- Login or register to post comments
- Printer-friendly version
- arungupta's blog
- 1801 reads





