假设我们有一个带有以下方法的 @RestController ( Spring Boot 1.3.5.RELEASE ):
@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public Map<String, String> helloWorld(@RequestBody Map<String, String> m) {
m.put("Hello", "2");
m.put("World", "1");
return m;
}
@Test 使用 TestRestTemplate :
RestTemplate restTemplate = new TestRestTemplate();
@Test
public void testHelloWorld() {
Map<String, String> request = new HashMap<>();
request.put("Hello", "1");
request.put("World", "2");
Map<String, String> respons = this.restTemplate.postForObject("/helloworld", request, Map.class);
}
如何打印/记录发送/接收的实际请求/响应 ?
即如何打印/记录 request / respons 的序列化版本?
答案 0 :(得分:0)
这在请求过滤器级别上是可用的:
public class YourCustomFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// your code here
}
@Override
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// your code here
}
}
但是,问题是:你真的想这样做,因为什么?请记住,这确实很容易出错。
答案 1 :(得分:0)
您可以使用aspect来记录请求和响应
请求的示例摘录:
@Aspect
@Component
public class InputLoggerAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(InputLoggerAspect.class);
@Autowired
private ObjectMapper objectMapper;
@Before(value = "valueToPointCut")
public void before(JoinPoint pointcut) throws Exception {
Object[] args = pointcut.getArgs();
for (Object object : args) {
LOGGER.info("{}:{}", object.getClass(), objectMapper.writeValueAsString(object));
}
}
}