java – 在JAX-RS资源方法中获取原始请求体

如何从JAX-RS资源方法访问原始请求主体,如java.io.InputStream或byte []?我希望容器绕过特定资源类或方法的任何MessageBodyReader,但我在项目中有其他资源应该使用一些MessageBodyReader.

我试过这个,但它会调用已注册的MessageBodyReaders并且无法将结果分配给InputStream(与byte []相同的问题).

@POST
public Response post(@Context HttpHeaders headers, InputStream requestBody) {
    MediaType contentType = headers.getMediaType();
    // ... 
}

我也尝试了这个,但是容器无法初始化此错误:

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();
    // ... 
}

该方法位于子资源类中,该子资源类是在另一个资源类中使用@Path注释的方法创建的.

我正在使用Jersey 1.11.

最佳答案
只是这有助于任何人

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

    }

转载注明原文:java – 在JAX-RS资源方法中获取原始请求体 - 代码日志