The use of caching functionality in the Android HTTP expansion pack Okhttp _android

Source: Internet
Author: User

Okhttp can cache the contents of an HTTP response on disk. When an HTTP request is made, if the response to the request has been cached and has not expired, Okhttp will directly use the response content in the cache without actually issuing an HTTP request to the remote server. You need to specify the size of a disk directory and cache when creating the cache. In Listing 8, after the Cache object is created, it is set through the Okhttpclient Setcache. The Cacheresponse and Networkresponse methods of the Response object can get the cached response and the response from the actual HTTP request. If the response from the request is from a real network request, the return value of the Cacheresponse method is null, and if the response is from the cache, the Networkresponse return value is null. Okhttp follows the requirements of the HTTP protocol when caching, so it is possible to control the cache time of the response through standard HTTP header cache-control.

To set an example of response caching

 public class Cacheresponse {public static void main (string[] args) throws IOException
  {int cacheSize = 100 * 1024 * 1024;
  File cachedirectory = files.createtempdirectory ("cache"). ToFile ();
  Cache cache = New cache (cachedirectory, cacheSize);
  Okhttpclient client = new Okhttpclient ();

  Client.setcache (cache);

  Request Request = new Request.builder (). URL ("http://www.baidu.com"). Build ();
  Response Response = client.newcall (Request). Execute ();
  if (!response.issuccessful ()) {throw new IOException ("Server-side error:" + response);
  } System.out.println (Response.cacheresponse ());
  System.out.println (Response.networkresponse ()); }
}

Cache-control
Cache-control Specifies the caching mechanism that the request and response follow. Setting Cache-control in a request message or in a response message does not modify the caching process during another message handling process. There are several following caching instructions at request:
Public indicates that the response can be cached by any buffer.
Private indicates that the entire or partial response message for a single user cannot be handled by the shared cache. This allows the server to simply describe a partial response message from the user, which is not valid for other users ' requests.
(1) No-cache indicates that the request or response message cannot be cached
(2) No-store is used to prevent important information from being inadvertently released. Sending in a request message will not use caching for both request and response messages.
(3) Max-age indicates that the client can receive a response that is not longer than the specified time in seconds.
(4) Min-fresh indicates that the client can receive response times that are less than the current time plus a specified time.
(5) Max-stale instructs the client to receive a response message that exceeds the timeout period. If you specify a value for the Max-stale message, the client can receive a response message that exceeds the specified value for the timeout period.
CacheControl Class Detailed Description:
1.) commonly used functions: The following code, which has been added to the annotation is not explained, each function is corresponding to a cache instruction settings

Final Cachecontrol.builder Builder = new Cachecontrol.builder ();
     Builder.nocache ();//Do not use cache, all go network
      builder.nostore ();//no cache, no cache
      builder.onlyifcached ();//Caching only
      Builder.notransform ()//Prohibit transcoding
      builder.maxage (timeunit.milliseconds);//indicates that the client can receive a response that is no longer than the specified time.
      Builder.maxstale (timeunit.seconds);//indicates that the client can receive response messages that exceed the timeout period
      Builder.minfresh (timeunit.seconds); Indicates that the client can receive response times that are less than the current time plus a specified time.
      CacheControl cache = Builder.build ();//cachecontrol

2.) Two CacheControl constants are described:

     Cachecontrol.force_cache; Just use the cache
      cachecontrol.force_network;//just use the network


For example, we set a cachecontrol that is valid for 10 seconds.

      Final Cachecontrol.builder Builder = new Cachecontrol.builder ();
      Builder.maxage (timeunit.milliseconds);
      CacheControl cache = Builder.build ();

3. How to use when requesting

Final Cachecontrol.builder Builder = new Cachecontrol.builder ();
      Builder.maxage (Timeunit.milliseconds);
      CacheControl cache = Builder.build ();
      Final request = new Request.builder (). CacheControl (cache). URL (requesturl). build (); Final call = Mokhttpclient.newcall (request);//Call.enqueue (new Callback () {@Override public V
          OID OnFailure (call call, IOException e) {failedcallback ("Access Failed", CallBack);
        LOG.E (TAG, e.tostring ()); @Override public void Onresponse (call call, Response Response) throws IOException {if (respo
            Nse.issuccessful ()) {String string = Response.body (). String ();
            LOG.E (TAG, "response----->" + string);
          Successcallback ((T) string, callBack);
          else {failedcallback ("Server Error", CallBack);
      }
        }
      });
    return call;
    catch (Exception e) {log.e (TAG, e.tostring ()); }

 

If the cache is not in the past will return directly to the cache without initiating a network request, if expired will automatically initiate a network request. Note: If you use Force_cache and network response requirements, OKHTTP will return a 504 hint telling you that the request response is not satisfied. So we add a judgment to use without the network

    Determine whether the network is connected
    Boolean connected = networkutil.isconnected (context);
     if (!connected) {
       request = Request.newbuilder (). CacheControl (Cachecontrol.force_cache). build ();
     

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.