Obtaining raw request body in JAX-RS resource method

前端 未结 3 765
-上瘾入骨i
-上瘾入骨i 2020-12-15 22:21

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

相关标签:
3条回答
  • 2020-12-15 23:00

    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();
    
        }
    
    0 讨论(0)
  • 2020-12-15 23:03

    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.

    0 讨论(0)
  • 2020-12-15 23:04

    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));
    }
    
    0 讨论(0)
提交回复
热议问题