简体   繁体   中英

Get size of serialized Request using Spring RestTemplate

I am using Spring and RestTemplate to send requests to a REST service. Is there a way to get the (byte)size of the actual request? Optimally it includes the size of the HTTP request including the size of the serialized myObject object for both GET and POST requests.

template.postForObject(restUrl, myObject, MyObject.class);
template.getForObject(restUrl, MyObject.class);

Basically I want to know how much data is actually transmitted.

Thanks!


[edit]:

Just to complete the answer, this is how you add the Interceptor to the RestTemplate. I also edited the LengthInterceptor to show the content length of the request instead of the response.

final List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>();
interceptors.add( new LengthInterceptor() );
template.setInterceptors( interceptors );

You can use interceptor to intercept the request/response similarly to filter in java servlet. You have to read the response and using getHeaders().getContentLength() you'll get the body length:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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