获得原始的请求体JAX-RS资源的方法(Obtaining raw request body in

2019-08-31 18:46发布

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

我已经试过这一点,但它会调用注册MessageBodyReader S和无法分配结果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在另一资源类注释。

我使用的泽西1.11。

Answer 1:

只是柜面这可以帮助任何人

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

    }


Answer 2:

这对我的作品:

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


Answer 3:

我发现,注入的HttpServletRequest没有工作的原因,那是因为我没有运行我在新泽西测试框架代码,而不是内妥善Servlet容器。 如果我在一个适当的Servlet容器运行它的工作原理。

可惜的是,有获取原始请求身体没有纯粹的JAX-RS的方式。



文章来源: Obtaining raw request body in JAX-RS resource method