Android Discovery based on okhttp build your own Web request <Cache-Control> (iv)

Source: Internet
Author: User

Objective:

The previous study has basically been able to complete the development requirements, but in the project will sometimes encounter the request to do a cache, when the network is not a priority to load the local cache, based on this requirement we learn to have been okhttp Cache-control.

Cache-control:

CACHE-CONTROL Specifies the caching mechanism that requests and responses follow. Setting Cache-control in a request message or response message does not modify the caching process in another message processing process. There are several cache directives at the time of the 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 shared with the cache. This allows the server to simply describe a partial response message for the user, and this response message is not valid for another user's request.
    • No-cache indicates that a request or response message cannot be cached
    • No-store is used to prevent the inadvertent release of important information. Sending in the request message will make the request and response messages do not use the cache.
    • Max-age indicates that the client can receive a response that is not longer than the specified time (in seconds).
    • Min-fresh indicates that the client can receive a response that is less than the current time plus a specified time.
    • Max-stale indicates that the client can 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.java class Introduction: 1.) Commonly used functions: The following code, which has been added to the comments are not explained, each function is corresponding to a cache instruction set
           FinalCachecontrol.builder Builder =NewCachecontrol.builder (); Builder.nocache ();//do not use the cache, all go networkBuilder.nostore ();//do not use cache, nor store cacheBuilder.onlyifcached ();//Use only cacheBuilder.notransform ();//No transcodingBuilder.maxage (ten, timeunit.milliseconds);//indicates that the client can receive a response that has a lifetime of not greater than the specified time. Builder.maxstale (ten, timeunit.seconds);//indicates that the client can receive a response message beyond the timeout periodBuilder.minfresh (ten, timeunit.seconds);//indicates that the client can receive a response time that is less than the current time plus the specified time. CacheControl cache = Builder.build ();//CacheControl
2.) Two CacheControl constants introduced:
            // just use the cache            Cachecontrol.force_network; // just use the network

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

            Final New Cachecontrol.builder ();            Builder.maxage (ten, timeunit.milliseconds);             = Builder.build ();
3.) How to use when requesting
FinalCachecontrol.builder Builder =NewCachecontrol.builder (); Builder.maxage (10, Timeunit.milliseconds); CacheControl Cache=Builder.build (); FinalRequest Request =NewRequest.builder (). CacheControl (cache). URL (requesturl). build (); FinalCall call = Mokhttpclient.newcall (request);//Call.enqueue (NewCallback () {@Override Public voidonfailure (call call, IOException e) {failedcallback ("Access Failed", CallBack);                LOG.E (TAG, e.tostring ()); } @Override Public voidOnresponse (call call, Response Response)throwsIOException {if(Response.issuccessful ()) {String string =response.body (). String (); LOG.E (TAG,"Response----->" +string);                    Successcallback ((T) string, callBack); } Else{failedcallback ("Server Error", CallBack);            }                }            }); returnCall ; } Catch(Exception e) {log.e (TAG, e.tostring ()); }

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

       // determine if the network is connected        Boolean connected = networkutil.isconnected (context);          if (! connected) {             = request.newbuilder (). CacheControl (Cachecontrol.force_cache). build ();          }
OKHTITP Knowledge Extension:1.) Interceptor Interceptor, known as the interception operation, is used to intercept the request to do some special processing, for example: above we use the CacheControl, How do we intercept a request to use Cachecontrol.force_cache when the network is unavailable;
Okhttpclient.builder Newbuilder =Mokhttpclient.newbuilder (); Newbuilder.addinterceptor (NewInterceptor () {@Override PublicResponse Intercept (Chain Chain)throwsIOException {Request Request=chain.request (); BooleanConnected =networkutil.isconnected (context); if(!connected) {Request=Request.newbuilder (). CacheControl (Cachecontrol.force_cache). build (); } Response Response=chain.proceed (Request); returnresponse; }        });
2.) OkHttp provides support for user authentication. When the HTTP response status code is 401, OkHttp gets the new request object from the set Authenticator object and tries to make the request again. The Authenticate method in the Authenticator interface is used to provide the request object for authentication.
        New okhttpclient ();        Client.newbuilder (). Authenticator (new  Authenticator () {            @Override            public throws IOException {                = credentials.basic ("User", "password");                 return response.request (). Newbuilder ()                        header("Authorization", credential)                        . Build ();            }        }); 

Summary: Okhttp's simple use to this introduction is complete, as for many advanced use has yet to be researched. Next, we are going to study the use of okhttp with RETROFITDE.

Android Discovery based on okhttp build your own Web request <Cache-Control> (iv)

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.