我有一些具有如下方法签名的 JAX-RS Web 服务。是否可以打印出来自客户端的原始 JSON 请求和返回给客户端的原始 JSON 响应?
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response XXX(@Context HttpServletRequest request, Parameters requestParameters) {
...
}
提前致谢。
最佳答案
这可以通过请求过滤器为您完成。这是我的实现:
@Path("test")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class HelloResource {
private static final Logger log = Logger.getLogger(HelloResource.class);
@POST
@Path("/test")
public Response test(String body) {
Map<String, String> tmp = new HashMap<>();
tmp.put("test", "value");
return Response.ok(tmp).build();
}
}
用于测试的资源。只是把 body 当作一根绳子。
现在您可以注册一个 ContainerResponseFilter 和一个 ContainerRequestFilter。
这些过滤器将在请求前后被调用。 Before 将打印 incoming body,after 将打印 response body。
重要的是不要在响应过滤器中同时执行这两项操作,因为在执行响应过滤器时请求实体 Stream 已关闭。
那就是当你想要打印你的 body 时,例如像这样:
public class PrintFilter implements ContainerResponseFilter, ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
System.out.println("Response body: " + responseContext.getEntity());
}
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
String string = IOUtils.toString(requestContext.getEntityStream());
System.out.println("request body: " + string);
}
}
我正在使用 apache-commons 将请求流读入字符串。
对于我的 json 文件,看起来像这样:
artur@pandaadb:~/tmp/test$ cat 1.json
{
"eventType": 1,
"params": {
"field1" : 10
}
}
我可以做一个 curl ,看起来像这样:
artur@pandaadb:~/tmp/test$ curl -XPOST "localhost:9085/api/test/test" -H "Content-Type: application/json" --data @1.json
{"test":"value"}
这将打印到我的控制台:
request body: { "eventType": 1, "params": { "field1" : 10 }}
Response body: {test=value}
这显然只是众多解决方案中的一种。这适用于所有 json 内容类型(坦率地说,大多数其他内容类型也是我所期望的)。
希望对你有帮助,
阿图尔
关于java - 打印每个 JAX-RS 服务的 JSON 请求/响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38739708/