获取正文内容@Context HttpServletRequest java jersey

时间:2017-04-13 10:34:35

标签: java rest jersey

我正在使用Jersey,我试图通过我的方法访问请求体,这个问题非常类似于:

如何使用Jersey读取RESTful服务的请求正文?

身体价值发送给邮递员。

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

1 个答案:

答案 0 :(得分:0)

一种方法是创建一个过滤器(实现ContainerRequestFilter)并处理输入流。

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

  }

}