我使用Spring和RestTemplate将请求发送到REST服务。有没有办法获得实际请求的(字节)大小?最佳地,它包括HTTP请求的大小,包括GET和POST请求的序列化myObject
对象的大小。
template.postForObject(restUrl, myObject, MyObject.class);
template.getForObject(restUrl, MyObject.class);
基本上我想知道实际传输了多少数据。
谢谢!
[编辑]:
只是为了完成答案,这就是你如何将Interceptor添加到RestTemplate。我还编辑了LengthInterceptor以显示请求的内容长度而不是响应。
final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add( new LengthInterceptor() );
template.setInterceptors( interceptors );
答案 0 :(得分:0)
您可以使用拦截器拦截请求/响应,类似于java servlet中的过滤器。您必须阅读回复并使用getHeaders().getContentLength()
获得正文长度:
public class LengthInterceptor implements ClientHttpRequestInterceptor {
@Override
public ClientHttpResponse intercept( HttpRequest request, byte[] body, ClientHttpRequestExecution execution ) throws IOException {
ClientHttpResponse response = execution.execute( request, body );
long length = response.getHeaders().getContentLength();
// do something with length
return response;
}
}