How to read JSON request body in Jersey

白昼怎懂夜的黑 提交于 2019-12-03 06:23:41
vladimir83

Here is an example for Jersey 2.0, just in case someone needs it (inspired by futuretelematics). It intercepts JSON and even allows to change it.

@Provider
public class MyFilter implements ContainerRequestFilter {

    @Override
    public void filter(ContainerRequestContext request) {
        if (isJson(request)) {
            try {
                String json = IOUtils.toString(req.getEntityStream(), Charsets.UTF_8);
                // do whatever you need with json

                // replace input stream for Jersey as we've already read it
                InputStream in = IOUtils.toInputStream(json);
                request.setEntityStream(in);

            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

    }

    boolean isJson(ContainerRequestContext request) {
        // define rules when to read body
        return request.getMediaType().toString().contains("application/json"); 
    }

}

One posibility is to use a ContainerRequestFilter that's called before your method is invoked:

public class MyRequestFilter 
  implements ContainerRequestFilter {
        @Override
    public ContainerRequest filter(ContainerRequest req) {
            // ... get the JSON payload here
            return req;
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!