Teach you to write the Android network framework request configuration with response cache

Source: Internet
Author: User

Objective

In the first three articles that teach you about the Android network framework, from the basic structure to the code implementation, we analyze how a simple network framework should work, and how to handle the code in the face of a variety of requirements, and learn some simple object-oriented design principles while in-depth understanding of the network framework. As the first post says, the Simplenet framework refers to the volley implementation, and even some class names are the same. Our goal is not to reinvent the wheel, but to learn the wheel making process to achieve the goal of self-improvement. Simplenet is just a simple network framework implementation, without rigorous testing and market testing, not recommended for use in the project, of course, if you feel that there is no problem, in the case of testing can also be used in their own projects.

Request configuration with HTTPS

When executing HTTP requests, we often need to configure HTTP requests, such as timeout configuration and HTTPS configuration. Simplenet here only makes a simple configuration, if there are more requirements, please do it yourself. Because HttpClient and httpurlconnection belong to a different class family, their configuration for HTTPS does not have a common type, so there is no abstraction here, Instead, two configuration classes are created for two httpclient and HttpURLConnection, where Httpclientconfig is the Httpclientstack configuration class, The Httpurlconnconfig is the Httpurlconnstack configuration class.

For example, when configuring HTTPS, HttpClient's sslsocketfactory package is org. Apache. HTTP. Conn. SSL. Sslsocketfactory, HttpURLConnection's sslsocketfactory package is javax. NET. SSL. Sslsocketfactory. This is a different implementation of the Apache and Android teams, so it is not a good idea to make an abstraction layer, which we use two configuration classes to configure.

To configure HTTPS with HttpClient, refer to the method using HTTPS in HttpClient, configure HTTPS when using Httpurlconnstack to perform HTTPS requests, refer to Android network programming--https Do not verify the certificate method (Trust all certificates).

For example, at less than API 9 o'clock, the user can configure sslsocketfactory through httpclientconfig and then get the sslsocketfactory of the configuration class when the request is executed to set the httpclient.

Package Org.simple.net.config;import Javax.net.ssl.hostnameverifier;import javax.net.ssl.sslsocketfactory;/** * This is the configuration class for the sslsocketfactory and hostnameverifier that are set for HTTPS requests when using Httpurlstack to perform requests, refer to * http://blog.csdn.net/xyz_lmn/ article/details/8027334,http://www.cnblogs.com/* vus520/archive/2012/09/07/2674725.html, * * @author mrsimple * *     public class Httpurlconnconfig extends Httpconfig {private static Httpurlconnconfig Sconfig = new Httpurlconnconfig ();    Private sslsocketfactory msslsocketfactory = null;    Private Hostnameverifier mhostnameverifier = null;    Private Httpurlconnconfig () {} public static Httpurlconnconfig GetConfig () {return sconfig; }/** * Configure HTTPS request sslsocketfactory with Hostnameverifier * * @param sslsocketfactory * @param hostnameverif IER */public void Sethttpsconfig (Sslsocketfactory sslsocketfactory, Hostnameverifier hostnameverifier)        {msslsocketfactory = sslsocketfactory; Mhostnameverifier = HostnAmeverifier;    } public Hostnameverifier Gethostnameverifier () {return mhostnameverifier;    } public sslsocketfactory Getsslsocketfactory () {return msslsocketfactory; }}

When a request is executed in Httpclientstack, it is determined whether it is an HTTPS request, and if so it needs to get the sslsocketfactory configured in the configuration class, the code is as follows:

    /**     * If it is an HTTPS request, it is configured with a user-configured sslsocketfactory.     *      * @param request * *    private void Confighttps (Request<?> request) {        sslsocketfactory Sslsocketfactory = Mconfig.getsocketfactory ();        if (Request.ishttps () && sslsocketfactory! = null) {            Scheme sch = new scheme ("https", sslsocketfactory, 443);            Mhttpclient.getconnectionmanager (). Getschemeregistry (). Register (Sch);        }    

The HTTPS settings for Httpurlconnstack are similar and are not given.because there is no server, the configuration for HTTPS I have not been tested, if there is a problem, please debug yourself.


Response cache

in some cases, the data does not need to be fetched from the server each time, so we have added the response cache. This avoids unnecessary requests to waste traffic and improves the user experience. User can pass the request Setshouldcache(boolean shouldcache) The response method is used to set whether the request is cached or not cached if it is true.

When the request is executed, it is determined whether the response of the request is cached, and if so, the response is cached in memory. If the request is enabled for caching, it is determined whether the cache is included before the request, and if there is a cache, the cache results are fetched directly from the server. The following is the code that executes the network request in Networkexecutor.

    @Override public void Run () {try {while (!isstop) {final request<?> Reque                st = Mrequestqueue.take ();                    if (request.iscanceled ()) {LOG.D ("# # #", "# # # Cancel Execution");                Continue                } Response Response = null;                if (Isusecache (Request)) {//from cache response = Mreqcache.get (Request.geturl ());                    } else {//Get data from the network response = mhttpstack.performrequest (request); If the request requires caching, then the request is cached to Mresponsecache if (Request.shouldcache () && issuccess (r                    Esponse)) {Mreqcache.put (Request.geturl (), response);            }}//Distribution Request Results Mresponsedelivery.deliveryresponse (request, response); }} catch (Interruptedexception e) {log.i ("", "# # # Requests(the sender exits "); }    }

Response Cache

For caching, we have added a simple cache interface. The interface is a generic interface, and the type of key and value are generic. It is designed to be generic because we will use it in subsequent frameworks, and the subsequent Imageloader framework will build a picture loading framework based on the Simplenet framework, which will also use the cache interface, but its type is different, so we use generics to ensure its scalability.

/** * Request Cache interface *  * @author mrsimple * @param <K> Key type * @param <V> value type */public interface Cache<k, v> {public    V get (K key);    public void put (K key, V value);    public void Remove (K key);

For the caching of network requests, our implementation is the Lrumemcache class, which caches response request results according to the LRU rules. The code is as follows:

/** * Cache request results into memory * * @author mrsimple */public class Lrumemcache implements Cache<string, response> {/** *    Reponse Cache */Private lrucache<string, response> Mresponsecache;        Public Lrumemcache () {//calculates the maximum memory that can be used for final int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);        Take one-eighth of the available memory as the cache final int cacheSize = MAXMEMORY/8; Mresponsecache = new lrucache<string, response> (cacheSize) {@Override protected int sizeOf (St            Ring key, Response Response) {return response.rawdata.length/1024;    }        };    } @Override public Response get (String key) {return mresponsecache.get (key);    } @Override public void put (String key, Response Response) {mresponsecache.put (key, Response);    } @Override public void Remove (String key) {mresponsecache.remove (key); }}

The Cache class object is shared by each networkexecutor, and it is defined in Networkexecutor as follows:

    /**     * Request Cache     *    /private static cache<string, response> Mreqcache = new Lrumemcache ();

In this way, multiple networkexecutor can have the same cache.


GitHub Address

Simplenet Network Framework


ConclusionThe Android Network framework is over, and because of the company project, a lot of things are written more casually, but no matter how good or bad it is, it is a well-intentioned share. As stated above, our aim is not to reinvent the wheel, but to improve our technical, design, and abstraction skills as we learn to invent wheels. Or we can learn to realize this network framework, to understand the meaning of "interface-oriented programming, not for implementation-oriented programming." As Guo Lin said, writing code to a certain stage, more important is to read the code. From the good code to learn the excellent design and implementation, this is from the yard to engineer a necessary stage. when you can appreciate the beauty of software, you have come to a new stage. You can realize the beauty of design, the beauty of architecture, the good design in your eyes is beautiful, not just a bunch of messy but can realize the function of the code, you can be satisfied. Everyone is from the rookie slowly progress, nothing is not overnight. I write this series of blog, just hope in self-promotion at the same time can help some of the colleagues need help, although I level is very limited, but can share their own experience to others, even said to help others, that is the purpose of this series.

Teach you to write the Android network framework request configuration with response cache

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.