这可以通过请求过滤器来完成。这是我的实施:
@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。
这些过滤器将在请求前后被调用。在打印来袭的身体之前,会打印响应身体。
因为在响应过滤器执行时关闭了请求实体流,所以在响应过滤器中不要执行这两个操作非常重要。
这是当你想打印你的身体,例如,像这样:
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文件,看起来就像是:
[email protected]:~/tmp/test$ cat 1.json
{
"eventType": 1,
"params": {
"field1" : 10
}
}
我可以卷曲,看起来像这样:
[email protected]:~/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内容类型(坦率地说大多数其他内容类型以及我期望的)。
希望帮助,
阿图尔
回访JSON'返回Response.ok(returnedJsonString,MediaType.APPLICATION_JSON).build();' –
你误解了我的要求。我想打印出来自客户端的JSON请求,并打印出返回给客户端的JSON响应。例如,如果客户端发送{“x”:“123”},那么我希望能够打印出这个确切的字符串,用于调试目的。 – user3573403