Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get response header OkHttp

I need to check response header of HTTP request using OkHTTP library. before loading data I need to check it's last update time. The problem in that that the response body is about 2 MB so I need to get only Last-Modified header. Is it possible to load only response header without response body to increase the speed of the program`s RESTful actions?

like image 332
Near1999 Avatar asked Oct 13 '15 13:10

Near1999


2 Answers

You can send a HTTP HEAD request which only retrieves the headers. You only need to check if your server application supports HEAD requests.

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
(http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html)

Example for OkHttp:

String url = ...
Request request = new Request.Builder().url(url).head().build();
like image 172
wero Avatar answered Sep 28 '22 18:09

wero


The response body is streamed, so you can make the regular request, read the headers, and then decide whether or not to consume the body. If you don’t want the body, you can close() it without much waste.

There is a slight cost to the server to serve a response that might be abandoned. But the overall cost will be lower than making a HEAD and then a GET request unless you expect abandon a significant fraction (say > 90%) of requests.

like image 32
Jesse Wilson Avatar answered Sep 28 '22 17:09

Jesse Wilson