获取响应 header OkHttp

Get response header OkHttp

我需要使用 OkHTTP 库检查 HTTP request 的响应 header。在加载数据之前,我需要检查它的上次更新时间。问题在于响应 body 大约是 2 MB,所以我只需要得到 Last-Modified header。是否可以仅加载响应 header 而不加载响应 body 以提高程序 RESTful 操作的速度?

您可以发送仅检索 headers 的 HTTP HEAD 请求。您只需要检查您的服务器应用程序是否支持 HEAD 请求。

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)

OkHttp 示例:

String url = ...
Request request = new Request.Builder().url(url).head().build();

响应 body 是流式传输的,因此您可以发出常规请求,读取 headers,然后决定是否使用 body。如果你不想要 body,你可以 close() 它没有太多浪费。

服务器提供可能被放弃的响应的成本很小。但总体成本将低于发出 HEAD 然后发出 GET 请求,除非您预计会放弃很大一部分(比如 > 90%)的请求。