John
John

Reputation: 371

How do I access the HTTP request?

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?

Upvotes: 33

Views: 32286

Answers (3)

user4875457
user4875457

Reputation:

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;
}

Upvotes: 1

sdorra
sdorra

Reputation: 2392

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
}

Upvotes: 55

Jan Thom&#228;
Jan Thom&#228;

Reputation: 13604

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.

Upvotes: 1

Related Questions