How to write the request configuration and Response cache of the Android network framework, androidresponse

Source: Internet
Author: User

How to write the request configuration and Response cache of the Android network framework, androidresponse
Preface

In the first three articles that teach you to write the Android network framework, we have analyzed how a simple network framework works from the basic structure to code implementation, and how to handle the code in the face of all kinds of requirements, while learning some simple object-oriented design principles while having a deep understanding of the network framework. As mentioned in the first blog post, the SimpleNet framework references Volley implementation, and even some class names are the same. Our goal is not to re-invent the wheel, but to improve ourselves by learning the process of making the wheel. SimpleNet is just a simple network framework implementation, without strict tests and market tests. We do not recommend that you use it in projects. Of course, if you think there is no problem, it can also be used in your own projects after testing.

Request configuration and https

When executing an http request, we often need to configure the http request, such as timeout configuration and https configuration. SimpleNet only makes simple configuration here. If you have more requirements, implement it on your own. Because HttpClient and HttpURLConnection belong to different class families, their Https configuration does not have a public type, so there is no abstraction here, two configuration classes are created for HttpClient and HttpURLConnection. HttpClientConfig is the configuration class of HttpClientStack, while HttpUrlConnConfig is the configuration class of HttpUrlConnStack.

For example, when https is configured, the package of the SSLSocketFactory of httpClient is org. apache. http. conn. ssl. SSLSocketFactory, while the package of SSLSocketFactory of HttpURLConnection is javax.net. ssl. SSLSocketFactory. This is a different implementation of apache and Android teams, so it is difficult to make an abstraction layer. Here we use two configuration classes for configuration.

For https configuration when using HttpClient, refer to the HTTPS method in httpclient. for https configuration when using HttpUrlConnStack to execute https requests, refer to Android Network Programming-https does not verify the certificate method (trust all certificates ).

For example, if the value is lower than api 9, you can use HttpClientConfig to configure SSLSocketFactory, and then get the SSLSocketFactory of the configuration class to set HttpClient when executing the request.

Package org.simple.net. config; import javax.net. ssl. hostnameVerifier; import javax.net. ssl. SSLSocketFactory;/*** this is the configuration class for SSLSocketFactory and HostnameVerifier set for https requests when using HttpUrlStack to execute 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 callback (); private SSLSocketFactory response = null; private HostnameVerifier mHostnameVerifier = null; private response () {} public static HttpUrlConnConfig getConfig () {return sConfig ;} /*** configure the SSLSocketFactory and HostnameVerifier of the https request ** @ param sslSocketFactory * @ param hostnameVerifier */public void setHttpsConfig (SSLSocketFactory sslSocketFactory, HostnameVerifier hostnameVerifier) {Signature = signature; mHostnameVerifier = hostnameVerifier;} public HostnameVerifier getHostnameVerifier () {return mHostnameVerifier;} public SSLSocketFactory getSslSocketFactory () {return mSslSocketFactory ;}}

When a request is executed in HttpClientStack, the system determines whether the request is an https request. If yes, you need to obtain the SSLSocketFactory configured in the configuration class. The Code is as follows:

/*** For https requests, use the SSLSocketFactory configured by the user to configure. ** @ 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 of HttpUrlConnStack are similar. Because there is no server, I have not tested the Https configuration. If you have any problems, debug it on your own.


Response Cache

In some cases, data does not need to be retrieved from the server every time, so we have added the Response cache. In this way, unnecessary requests can be avoided, and the user experience can be improved. You can use the setShouldCache (boolean shouldCache) method of the Request to set whether to cache the Request's Response. If it is true, the Request is cached; otherwise, the Request is not cached.

When a request is executed, the system determines whether the request's Response is cached. If yes, the Response is cached in the memory. If the cache is enabled for the request, the request determines whether the request contains a cache. If there is a cache, the cache result is obtained directly. If there is no cache, the request is obtained from the server. The following code executes the network request in NetworkExecutor.

@ Override public void run () {try {while (! IsStop) {final Request <?> Request = mRequestQueue. take (); if (request. isCanceled () {Log. d ("####", "### canceled"); continue;} Response response = null; if (isUseCache (request )) {// obtain response = mReqCache from the cache. get (request. getUrl ();} else {// get data from the network response = mHttpStack. required mrequest (request); // if the request needs to be cached, the request is cached to mResponseCache if (request. shouldCache () & isSuccess (response) {mReqCache. put (request. getUrl (), response) ;}// the request result is mResponseDelivery. deliveryResponse (request, response) ;}} catch (InterruptedException e) {Log. I ("", "### request the distributor to exit ");}}

Response Cache

For caching, we added a simple cache interface. This interface is a generic interface, and the key and value types are generic. The design is generic because it will be used in subsequent frameworks. The subsequent ImageLoader framework will build an image loading framework based on the SimpleNet framework, and cache interfaces will also be used, however, 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 cache of network requests, we implement the LruMemCache class, which caches the Response Request results according to the LRU rules. The Code is as follows:

/*** Cache the request results to the memory ** @ author mrsimple */public class LruMemCache implements Cache <String, response> {/*** Reponse cache */private LruCache <String, Response> mResponseCache; public LruMemCache () {// calculate the maximum memory available final int maxMemory = (int) (Runtime. getRuntime (). maxMemory ()/1024); // take 1/8 of the available memory as the cache final int cacheSize = maxMemory/8; mResponseCache = new LruCache <String, Response> (cacheSize) {@ Override protected int sizeOf (String 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 );}}

Cache class objects are shared by NetworkExecutor. They are defined in NetworkExecutor as follows:

/*** Request Cache */private static Cache <String, Response> mReqCache = new LruMemCache ();

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


Github address

SimpleNet network framework


Conclusion The Android network framework is over now. For the company's project reasons, many things are relatively casual, but whether well written or not, it is always a good sharing. As mentioned above, our purpose is not to re-invent the wheel, but to improve our technical, design, and abstract capabilities while learning to invent the wheel. In other words, we can understand the meaning of the phrase "interface-oriented programming rather than implementation programming" in the process of learning and implementing this network framework. As Guo Lin said, when writing code to a certain stage, it is more important to read the code. Learning from excellent code to excellent design and implementation is a necessary stage from codenong to engineers. When you understand the beauty of software, it means you have reached a new stage. You can appreciate the beauty of design and architecture. In your eyes, excellent design is beautiful, not just a bunch of messy code that can implement functions, you can satisfy them. Everyone is coming from cainiao, and nothing can happen overnight. I am writing this series of blog posts, but I hope that I can help some colleagues who need help while improving myself. Although I have a limited level, I can share my experiences with others, even helping others is the original intention of this series.

Related Article

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.