这可以通过请求过滤器为您完成。这是我的实现:
@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();
}
}
用于测试的资源。只是把身体当作一个字符串。
现在您可以注册一个 ContainerResponseFilter 和一个 ContainerRequestFilter。
这些过滤器将在请求之前和之后调用。之前将打印传入的正文,之后将打印响应正文。
重要的是不要在响应过滤器中同时执行这两种操作,因为请求实体 Stream 在执行响应过滤器时已关闭。
那是你想要打印你的身体的时候,例如。像这样:
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
}
}
我可以做一个卷曲,看起来像这样:
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 内容类型(坦率地说,我期望的大多数其他内容类型也是如此)。
希望对你有帮助,
阿图尔