繁体   English   中英

在GET / POST / PUT调用之后,如何从RestTemplate获得转换后的请求?

[英]How do you get a converted request from RestTemplate after a GET/POST/PUT call?

使用Spring的RestTemplate对端点进行POST或GET调用,我没有任何问题。 我还将消息转换器设置为JSON(MappingJacksonHttpMessageConverter),没有问题。

我的问题是,我该如何处理发送的已转换请求?

例如,如果我这样做:

ResponseEntity<T> result = this.restTemplate.postForEntity("http://{endpoint_url...}", dtoEntryObj, SomeDTO.class);

如何获取发送到端点的JSON?

RestTemplate还可以发送json以外的其他格式。 为了获得请求的实际内容,您将需要实现自己的ClientHttpRequestInterceptor并使用RestTemplate#setInterceptors()进行注册。

就像是

RestTemplate template = new RestTemplate();
ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body,
            ClientHttpRequestExecution execution) throws IOException {
        // you have access to the body
        // do something with it
        return execution.execute(request, body);
    }
};
template.setInterceptors(Arrays.asList(interceptor));

请注意,对于json, RestTemplate使用MappingJackson2MessageConverter ,该MappingJackson2MessageConverter在内部使用ObjectMapper 如果上述解决方案不适合您,则可以对其进行仿真。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM