Android: the cache server data is stored locally.

Source: Internet
Author: User

Android: the cache server data is stored locally.

 

Two open-source code implementation ideas to simplify implementation

Two open source codes

It's enough. You don't have to write it yourself. The file is very small.
-The reservoir cache object is a string;
-Disklrucache: an SD card access tool;

Implementation idea

That is, the interface string is cached locally. It is not necessarily a network cache. You can specify any desired string for storage. If you want to use the database, you can use it to reduce the load pressure on the server.

The cache management method is embedded when the interface is called normally, which does not affect the previous Code and is easy to replace. Different interfaces can customize the cache expiration time, this time can be the server interface time or the local dead time. The loading logic is to make an MD5 key after all the data in the interface field is toString () each time, at the same time, the write time and cache time are saved. The cache is available based on the current time, write time, and cache time;

Because it is very simple, it can take a little time to do better. For example, if different interfaces are used for different times, the cache is used after full use of the cache or expiration, and the cache is used after the network is loaded, the write is required again;

For different projects at different network layers, I wrote one before network loading. Here:
Http://blog.csdn.net/intbird/article/details/38338623

Simplified Implementation

The cache does not require a large amount of additional information, so the method for determining the storage time is not Map

    private final static int initialCapacity = 1*1024*1024;    private final static String key_time_mills = timeMills;    private static LinkedHashMap
  
    cacheTimeMills;    private final static String key_time_valid = timeValid;    private static LinkedHashMap
   
     cacheTimeValid;
   
  

Rewrite interface code:

Protected boolean postCheck (final Context context, final boolean isShow, final String content, PostUrlInfo postUrlInfo, final RequestParams params, final IParser iParse, final INetCallBack callBack) {// if no cache is used, if (postUrlInfo. isEnabledCache () = false) return false; // try to obtain the cached data. If the cache has not expired, focus on the get method; String response = Reservoir. get (postUrlInfo. reqIndentKey, String. class); if (TextUtils. isEmpty (response) return false; // directly use the normal parsing method at the network layer, but mark it as cache loading // do not put it into the cache for some processing; dialogFragment dialogFragment = new ProgressDialogFragment (content); ParseResult parseResult = new ParseResult (); parseResult. isNetParse = false; parseTask task = new parseTask (dialogFragment, iParse, callBack, 0, getDefaultHeaders (params), response, postUrlInfo, parseResult); task.exe cute (); // perform the original network resolution. If the returned result is not loaded on the network, return true;} // refresh the original interface and encapsulate the Url Information to facilitate key calculation; protected void post (final Context context, final boolean isShow, final String content, String contents, final RequestParams params, final IParser iParse, final INetCallBack callBack) {PostUrlInfo urlInfo = new callBack (BaseURL, relativePath); post (context, isShow, content, urlInfo, params, iParse, callBack);} // Add a cache time extension interface to check the cacheTime CacheEnable () method; protected void post (long cacheTime, final Context context, final boolean isShow, final String content, String relativePath, final RequestParams params, final IParser iParse, final INetCallBack callBack) {// You can also use the host: port: ralaUrl method, which is encapsulated to check the situation. PostUrlInfo urlInfo = new PostUrlInfo (BaseURL, relativePath); urlInfo. setDefaultCacheTime (cacheTime); post (context, isShow, content, urlInfo, params, iParse, callBack);} // real loading mode protected void post (final Context context, final boolean isShow, final String content, final PostUrlInfo postUrlInfo, final RequestParams params, final IParser iParse, final INetCallBack callBack) {if (params = null) {return;} Logger. I (postUrlInfo. getPostUrl (); Logger. I (params. toString (); // calculate the key value of this interface, check the cache, getReqIdentifiter can remove the postKey to be calculated //, such as a random number at a time; postUrlInfo. reqIndentKey = getReqIdentifiter (postUrlInfo, params); if (postCheck (context, isShow, content, postUrlInfo, params, iParse, callBack) {return ;}// after loading using the network, put network layer data into the cache // Reservoir. put (postUrlInfo. reqIndentKey, // response, postUrlInfo. getDefaultCacheTime (); // load the client on the normal network. post (context, postUrlInfo. getPostUrl (), (org. apache. http. header []) getDefaultHeaders (params), params, null, new AsyncHttpResponseHandler (){};

A java aes-encrypted code file, EnDecrypt. java

Package com. anupcowkur. reservoir; import java. io. unsupportedEncodingException; import java. math. bigInteger; import java. security. invalidKeyException; import java. security. messageDigest; import java. security. noSuchAlgorithmException; import java. security. secureRandom; import javax. crypto. badPaddingException; import javax. crypto. cipher; import javax. crypto. illegalBlockSizeException; import javax. crypto. keyGenerator; import javax. crypto. noSuchPaddingException; import javax. crypto. secretKey; import javax. crypto. spec. secretKeySpec; public class EnDecrypt {public static String encrypts (String sourContent, String password) {try {byte [] encryptResult = encrypt (sourContent, password); return parseByte2HexStr (encryptResult );} catch (Exception ex) {return sourContent;} public static String decrypts (String cryContent, String password) {try {byte [] decryptFrom = parseHexStr2Byte (cryContent ); byte [] decryptResult = decrypt (decryptFrom, password); return new String (decryptResult);} catch (Exception ex) {return cryContent ;}} private static byte [] encrypt (String content, String password) throws failed, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {KeyGenerator kgen = KeyGenerator. getInstance (AES); kgen. init (128, new SecureRandom (password. getBytes (); SecretKey secretKey = kgen. generateKey (); byte [] enCodeFormat = secretKey. getEncoded (); SecretKeySpec key = new SecretKeySpec (enCodeFormat, AES); Cipher cipher = Cipher. getInstance (AES); // create a secret byte [] byteContent = content. getBytes (UTF-8); cipher. init (Cipher. ENCRYPT_MODE, key); // initialize byte [] result = cipher. doFinal (byteContent); return result; // encryption} private static byte [] decrypt (byte [] content, String password) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, badPaddingException {KeyGenerator kgen = KeyGenerator. getInstance (AES); kgen. init (128, new SecureRandom (password. getBytes (); SecretKey secretKey = kgen. generateKey (); byte [] enCodeFormat = secretKey. getEncoded (); SecretKeySpec key = new SecretKeySpec (enCodeFormat, AES); Cipher cipher = Cipher. getInstance (AES); // create a cipher. init (Cipher. DECRYPT_MODE, key); // initialize byte [] result = cipher. doFinal (content); return result; // encrypted} private static String parseByte2HexStr (byte buf []) {StringBuffer sb = new StringBuffer (); for (int I = 0; I <buf. length; I ++) {String hex = Integer. toHexString (buf [I] & 0xFF); if (hex. length () = 1) {hex = '0' + hex;} sb. append (hex. toUpperCase ();} return sb. toString ();} private static byte [] parseHexStr2Byte (String hexStr) {if (hexStr. length () <1) return null; byte [] result = new byte [hexStr. length ()/2]; for (int I = 0; I 

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.