I want to measure HTTP GET request time Call RestTemplate.getForObject without the time required for parsing the response
I had the same requirements. I want to know the server response time to determine how long it will take for the server to respond without processing the RestTemplate response. I added two interceptors to the HttpClientBuilder with the map so that I can measure the time between the request and the low-level response.
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); // Attach interceptors ResponseTimeInterceptor interceptor = new ResponseTimeInterceptor(); httpClientBuilder.addInterceptorFirst( (HttpRequestInterceptor) interceptor ); httpClientBuilder.addInterceptorFirst( (HttpResponseInterceptor) interceptor ); // Use client with RestTemplate or on its own HttpClient client = httpClientBuilder.build();
Here is a minimal double-action interceptor:
public class ResponseTimeInterceptor implements HttpRequestInterceptor, HttpResponseInterceptor { private final Map<HttpContext, Long> requestMap = new MaxSizeHashMap<>( 50 ); @Override public void process( HttpRequest httpRequest, HttpContext httpContext ) throws HttpException, IOException { requestMap.put( httpContext, System.currentTimeMillis() ); } @Override public void process( HttpResponse httpResponse, HttpContext httpContext ) throws HttpException, IOException { long startTime = requestMap.getOrDefault( httpContext, 0L ); long diff = System.currentTimeMillis() - startTime; System.out.println( "Response time: " + diff + "ms" ); } }
After the interceptor responder returns, the response data continues into the RestTemplate response handler.
Note. MaxSizeHashMap taken from fooobar.com/questions/223912 / ....
source share