Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 MessageBodyReaders 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
889 views
Welcome To Ask or Share your Answers For Others

1 Answer

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();

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...