How can I access the raw request body from a JAX-RS resource method, as java.io.InputStream
or byte[]
? I want the container to bypass any Mes
just incase this helps anyone
public Response doAThing(@Context HttpServletRequest request, InputStream requestBody){
BufferedReader reader = new BufferedReader(new InputStreamReader(requestBody));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();
return Response.ok().entity("{\"Submit\": \"Success\"}").build();
}
I found the reason that injecting HttpServletRequest did not work, it's because I did run my code in Jersey Test Framework, not within a proper Servlet container. It works if I run it in a proper Servlet container.
It is a pity that there is no pure JAX-RS way of getting the raw request body.
This works for me:
@POST
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
public Response doSomething(@Context HttpServletRequest request, byte[] input) {
log.debug("Content-Type: {}", request.getContentType());
log.debug("Preferred output: {}", request.getHeader(HttpHeaders.ACCEPT));
}