简体   繁体   中英

How does Resttemplate determine the status code of response before receiving it?

I'm new to Java and found a confusing behaviour related with RestTemplate.

It happened with an API returning large body (~5MB) over a quite slow network condition. The code is like below

ResponseEntity<MyEntity[]> result = restTemplate.exchange(url, HttpMethod.GET, entity, MyEntity[].class);

And also a ClientHttpRequestInterceptor is set to log before and after the request.

The confusing thing is that the after request log is logged only a while after remote server giving the response, and the HTTP Status code can be print in the log.

But the above statement took much more time to finally receive the data. Look inside the thread stack, it was reading data from socket.

I also look inside the resttemplate class and found:

response = request.execute();
handleResponse(url, method, response);
if (responseExtractor != null) {
    return responseExtractor.extractData(response);
}

It seems to extractData after the execute().

My doubt is:

  1. How does the client side know the status code even before get all the data? It just extracts necessary fields from the top packets?

  2. Since the server has already sent out the response, where the response data is stored during the process?

It stores the data that it receives from the underlying HTTP in memory.

Client side can know what's the status code because with HTTP you get the headers and status code first before the response body. But this doesn't matter with RestTemplate as it promises to give you an object of ResponseEntity in the end, which contains everything from the http response be it status codex headers or body.

RestTemplate is an abstraction over an HttpClient, most client's give you the option to implement callbacks for separate events like onHeadersReceived(), onStatusReceived() etc. But if you are using RestTemplate this means you don't require such fine grained control.

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