33

Say normally I have a REST method in Java

@POST 
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    public String showTime(@FormParam("username") String userName) {

:
:
:
}

which is fine. However, I'm wondering is there a way I can access the full HTTP request with Jersey such as

@POST 
    @Path("/test")
    @Produces(MediaType.APPLICATION_JSON)
    public String showTime(@FormParam("username") String userName,@XXXXXX String httpRequest) {

:
:
:
}

where some annotation would give me the full HTTP request to store in a variable. I have tried using @POST but it doesn't seem to work. Any suggestions?

Null
  • 1,950
  • 9
  • 30
  • 33
John
  • 371
  • 1
  • 4
  • 5

3 Answers3

55

You can use the @Context annotation:

@POST 
@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
public String showTime(
    @FormParam("username") String userName,
    @Context HttpServletRequest httpRequest
) {
    // The method body
}
Patrick M
  • 10,547
  • 9
  • 68
  • 101
sdorra
  • 2,382
  • 18
  • 16
  • 1
    Thanks sdorra that seems to do the trick. One last question, (can open this as a new question if needs be) how would i access the request body itself? – John Feb 28 '11 at 11:17
  • 1
    The body is controlled by the @Consumes Annotation: `@Path("body") public class BodyResource { @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public String get(String body) { System.out.println(body); return "The Body: ".concat(body); } }` – sdorra Feb 28 '11 at 12:12
  • if you are using maven you should have a dependency for: javax.servlet javax.servlet-api 3.1.0 – Paulo Oliveira Aug 28 '14 at 11:59
1

I wrote a helper function to address this. Simply extracts request headers and places them in a map.

private Map<String, String> extractHeaders(HttpServletRequest httpServletRequest) {

    Map<String, String> map = new HashMap<>();
    Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String header = headerNames.nextElement();
        map.put(header, httpServletRequest.getHeader(header));
    }

    return map;
}
1

If you want to get the request body, you could use the tip lined out in this post: How to get full REST request body using Jersey?

If you need to know more about the request itself, you could try the @Context annotation as mentioned by sdorra.

Community
  • 1
  • 1
Jan Thomä
  • 13,296
  • 6
  • 55
  • 83