简体   繁体   中英

get body content @Context HttpServletRequest java jersey

I am using Jersey and I am trying to access the request body in my method very similar to this question:

How do I read request body for a RESTful service using Jersey?

Body value send i with Postman.

   @Path("/updateanfrage")
       public class UpdateAnfrage extends ResourceConfig
        {
          private static final Logger log = Logger.getLogger(UpdateAnfrage.class);

        @POST
        @Consumes(MediaType.APPLICATION_XML)
        @Produces(MediaType.APPLICATION_XML)
        public UpdateInformation beschaffeUpdateInformation(ClientInformation clientinformation,
                @Context HttpHeaders headers, @Context UriInfo uriDetails,  @Context Request request, @Context HttpServletRequest requestContext) throws SecurityException, IOException
        {
             UpdateInformation updateinformation = new UpdateInformation();
             log.info("Method -- " + request.getMethod());
             log.info("Complete URI -- "+ uriDetails.getRequestUri().toString());
             log.info("Content Type -- "+ requestContext.getContentType());
            // log.info("Body -- "+ requestContext.getReader().lines());
             ...
             ...
            return updateinformation;
        }

One way to do that is to create a filter (that implements ContainerRequestFilter ) and process the input stream.

@Provider
@PreMatching
public class LoggingFilter implements ContainerRequestFilter{

  @Override
  public void filter(ContainerRequestContext req){

  //init logger
  final Logger logger = Logger.getLogger(UpdateAnfrage.class);

  BufferedReader br = new BufferedReader(new InputStreamReader(req.getEntityStream(),"UTF-8"));

  StringBuilder xml = new StringBuilder();
  String line;
  while ((line = br.readLine()) != null) {
            xml.append(line);
        }

   req.setEntityStream(new ByteArrayInputStream(xml.toString().getBytes("UTF-8")));
   logger.info(xml);

  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM