Httpresponsecache Network Cache Usage

Source: Internet
Author: User

Caches HTTP and HTTPS responses to the filesystem so they could be reused, saving time and bandwidth. This class supports HttpURLConnection and HttpsURLConnection ; there are no platform-provided cache for DefaultHttpClient or AndroidHttpClient .

Installing an HTTP response cache added at API level 13

Enable caching of all of your application's HTTP requests by installing the cache at application startup. For example, this code installs a ten MiB cache in the of the application-specific cache directory filesystem}:

Protected voidOnCreate(BundleSavedinstancestate) {
...
Try {
FileHttpcachedir= New File(Context.Getcachedir(), "http" );            long httpcachesize = 10 *1024 * 1024 //ten mib
           httpresponsecache. (httpcachedir, httpcachesize< Span class= "pun");
       
Catch (IOExceptionE) {
Log.I(TAG, "HTTP Response Cache installation failed:" +E);
}
}

Protected voidOnStop() {
...

       httpresponsecache cache Span class= "pun" >= httpresponsecache. Getinstalled        if (cache Span class= "pun" >!= null) {
           cache.flush ();        }
   }}

This cache would evict entries as necessary to keep it size from exceeding MiB. The best cache size was application specific and depends on the size and frequency of the files being downloaded. Increasing the limit may improve the "hit rate" but it may also just waste filesystem space!

For some applications it is preferable to create the cache in the external storage directory. There is no access controls on the external storage directory so it should is not being used for caches that could contain Private data. Although it often have more free space, external storage are optional And-even if available-can disappear during use. Retrieve the external cache directory using getExternalCacheDir() . If This method is returns NULL, your application should fall back to either not caching or caching on non-external storage. If The external storage is removed during use, the cache hits rate would drop to zero and ongoing cache reads would fail.

Flushing the cache forces its data to the filesystem. This ensures, responses written to the cache would be readable the next time the activity starts.

Cache optimization
To measure cache effectiveness, this class tracks three statistics:
    • Request Count:The number of HTTP requests issued since this cache is created.
    • Network Count:The number of those requests that required network use.
    • Hit Count:The number of those requests whose responses were served by the cache.
Sometimes a request would result in a conditional the cache hit. If The cache contains a stale copy of the response, the client would issue a conditional GET . The server would then send either the updated response if it had changed, or a short ' not modified ' response if the client ' s copy is still valid. Such responses increment both the network count and hit count.

The best-of-the-improve the cache hits rate is by configuring the Web server to return cacheable responses. Although this client honors all http/1.1 (RFC 2068) cache headers, it doesn ' t cache partial responses.

Force a Network Response
In some situations, such as after a user clicks a ' refresh ' button, it may be necessary to skip the cache, and fetch data directly from the server. To force a full refresh, add the no-cache directive:
connection.addRequestProperty("Cache-Control", "no-cache");
 
If It is an necessary to force a cached response to be validated by the server with the more efficient instead max-age=0 :
connection.addRequestProperty("Cache-Control", "max-age=0");
 
Force a Cache Response
Sometimes you "ll want to show resources if they is available immediately, but not otherwise. This can is used so your application can show something when waiting for the latest data to be downloaded. To restrict a request to locally-cached resources, add the only-if-cached directive:
  try { 
         connection. Addrequestproperty ( "Cache-control" , span class= "str" > "only-if-cached" );
         inputstream cached = Connection.          //the resource was cached! show It
  & nbsp  
catch (filenotfoundexception e) {
//The resource is not cached
}
}
This technique works even better in situations where a stale response is better than no response. To permit stale cached responses, use the max-stale directive with the maximum staleness in seconds:
Int Maxstale = 60 * 60 * Span class= "lit" >24 * 28  //tolerate 4-weeks stale 
          Connection. Addrequestproperty ( "Cache-control" , span class= "str" > "max-stale=" + Maxstale) ;
 
Working with Earlier releases
This class is added in Android 4.0 (Ice Cream Sandwich). Use reflection to enable the response cache without impacting earlier releases:
Try {
FileHttpcachedir= New File(Context.Getcachedir(), "http");
LongHttpcachesize= 10 * 1024 * 1024; Ten MiB
Class.Forname("Android.net.http.HttpResponseCache"
                   getmethod ( "install" , file., long.
                   < Span class= "pun". invoke (null, Httpcachedir, Httpcachesize        
catch (Exception httpresponsecachenotavailable) {
}}

Httpresponsecache Network Cache Usage

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.