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 MessageBodyReader
for a specific resource class or method, but I have other resources in the projects which should be using some MessageBodyReader
.
I have tried this, but it will invoke registered MessageBodyReader
s and fail to assign the result to InputStream
(same issue with byte[]
).
@POST
public Response post(@Context HttpHeaders headers, InputStream requestBody) {
MediaType contentType = headers.getMediaType();
// ...
}
I have also tried this, but then the container fails to initialize with this error:
SEVERE: The following errors and warnings have been detected with resource and/or provider classes: SEVERE: Missing dependency for method public javax.ws.rs.core.Response SomeResource.post(javax.servlet.http.HttpServletRequest) at parameter at index 0 SEVERE: Method, public javax.ws.rs.core.Response SomeResource.post(javax.servlet.http.HttpServletRequest), annotated with POST of resource, class SomeResource, is not recognized as valid resource method.
@POST
public Response post(@Context HttpServletRequest request) {
String contentType = request.getContentType();
InputStream requestBody = request.getInputStream();
// ...
}
The method is in a sub resource class, which is created from a method with a @Path
annotation in another resource class.
I am using Jersey 1.11.
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();
}
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));
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With