Android: Cache server data for local storage

Source: Internet
Author: User
Tags decrypt

Tagged with: android cache online cache for android™ local cache client Cache network data

Article Address: Http://blog.csdn.net/intbird

    • Two open source code
    • Realize the idea
    • Simple implementation of some simplified practices

Two open source code

It's enough, there's no need to write it, it's very small.
-Reservoir Cache object is a string;
-Disklrucache access SD card tool;

Realize the idea

That is, the interface string is cached locally, not necessarily the network cache, you can specify any desired string to save, if willing to use the database and so on, to see the need, to reduce the server load pressure

    • In the case of ensuring that the interface is properly invoked, the embedded cache management method does not affect the previous code and is easy to replace.
    • Different interfaces can customize the expiration time of the cache, which can be the time of the server interface, or the time of local death;
    • Load logic for each time the interface field all data ToString () after doing a MD5 as a key, while the write time and cache time to save, when the check out based on the current time and write time and cache time to determine whether the cache is available;
    • Because it is very simple this can take a bit of time to do a better point, such as different interfaces at different times, the full use of cache or cache expires after the use of the cache, waiting for the network to re-write after the completion of loading and so on;

      Different project different network layer, Network load before use wrote one, here:
      http://blog.csdn.net/intbird/article/details/38338623

Simple implementation of some simplified practices

does not require much extra information for caching, so it is not a map

to determine how long to swap

 private  final  static  int  initialcapacity = 1  *1024  *1024 ; private  final  static  String key_time_mills =  "Timemills" ; private  static  Linkedhashmap<string, long> cachetimemills; private  final  static  String key_time_valid =  "Timevalid" ; private  static  Linkedhashmap<string, long> cachetimevalid; 

Overwrite the interface code:

    protected Boolean Postcheck(FinalContext Context,Final BooleanIsshow,FinalString Content,posturlinfo Posturlinfo,FinalRequestparams params,FinalIparser Iparse,FinalInetcallback callBack) {//If the cache is not used, the Network load        if(Posturlinfo.isenabledcache () = =false)return false;//Try to get cached data, if the cache is not expired, focus on the Get method;String response = Reservoir.get (Posturlinfo.reqindentkey, String.class);if(Textutils.isempty (response))return false;//directly using the network layer Normal parsing method, but marked for cache loading        //Do not put cache, do some processing;Dialogfragment dialogfragment =NewProgressdialogfragment (content); Parseresult Parseresult =NewParseresult (); Parseresult.isnetparse =false; Parsetask task =NewParsetask (Dialogfragment, Iparse, CallBack,0, Getdefaultheaders (params), response,posturlinfo,parseresult); Task.execute ();//Do the original network parsing, the return is not in the network load;        return true; }//re-organize the original interface, encapsulate the URL information, convenient to calculate key;    protected void Post(FinalContext Context,Final BooleanIsshow,FinalString content,string RelativePath,FinalRequestparams params,FinalIparser Iparse,FinalInetcallback callBack) {Posturlinfo Urlinfo =NewPosturlinfo (Baseurl,relativepath);    Post (context, isshow, content,urlinfo, params, iparse, callBack); }//Add a cache time extension to the original interface, check the Cachetime cacheenable () method;    protected void Post(LongCacheTime,FinalContext Context,Final BooleanIsshow,FinalString content,string RelativePath,FinalRequestparams params,FinalIparser Iparse,FinalInetcallback callBack) {//can also use HOST:PORT:RALAURL way, has been packaged to see the situation;Posturlinfo Urlinfo =NewPosturlinfo (Baseurl,relativepath);        Urlinfo.setdefaultcachetime (CacheTime);    Post (context, isshow, content,urlinfo, params, iparse, callBack); }//Real load mode    protected void Post(FinalContext Context,Final BooleanIsshow,FinalString content,FinalPosturlinfo Posturlinfo,FinalRequestparams params,FinalIparser Iparse,FinalInetcallback callBack) {if(Params = =NULL) {return;        } logger.i (Posturlinfo.getposturl ()); Logger.i (Params.tostring ());//Calculate the key value of the secondary interface, check the cache, Getreqidentifiter can be removed to calculate        //Postkey, such as single-time random number;Posturlinfo.reqindentkey = Getreqidentifiter (posturlinfo,params);if(Postcheck (context, isshow, content,posturlinfo, params, iparse, CallBack)) {return; }//After using the network load, put the network layer data into the cache        //reservoir.put (Posturlinfo.reqindentkey,        //response,posturlinfo.getdefaultcachetime ());        //Normal Network LoadClient.post (Context, Posturlinfo.getposturl (), (org.apache.http.header[]) getdefaultheaders (params), params,NULL,NewAsynchttpresponsehandler () {};

A Java AES-encrypted code file Endecrypt.java

 PackageCom.anupcowkur.reservoir;ImportJava.io.UnsupportedEncodingException;ImportJava.math.BigInteger;ImportJava.security.InvalidKeyException;ImportJava.security.MessageDigest;ImportJava.security.NoSuchAlgorithmException;ImportJava.security.SecureRandom;ImportJavax.crypto.BadPaddingException;ImportJavax.crypto.Cipher;ImportJavax.crypto.IllegalBlockSizeException;ImportJavax.crypto.KeyGenerator;ImportJavax.crypto.NoSuchPaddingException;ImportJavax.crypto.SecretKey;ImportJavax.crypto.spec.SecretKeySpec; Public  class endecrypt {     Public StaticStringencrypts(String sourcontent,string password) {Try{byte[] Encryptresult = Encrypt (sourcontent, password);returnParsebyte2hexstr (Encryptresult); }Catch(Exception ex) {returnSourcontent; }    } Public  StaticStringdecrypts(String crycontent,string password) {Try{byte[] Decryptfrom = Parsehexstr2byte (crycontent);byte[] Decryptresult = Decrypt (Decryptfrom,password);return  NewString (Decryptresult); }Catch(Exception ex) {returnCrycontent; }    }Private Static byte[]Encrypt(string content, string password)throwsNoSuchAlgorithmException, Nosuchpaddingexception, Unsupportedencodingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception {keygenerator KGen = keygenerator.getinstance ("AES"); Kgen.init ( -,NewSecureRandom (Password.getbytes ())); Secretkey Secretkey = Kgen.generatekey ();byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key =NewSecretkeyspec (Encodeformat,"AES"); Cipher Cipher = cipher.getinstance ("AES");//Create a cryptographic device        byte[] bytecontent = Content.getbytes ("Utf-8"); Cipher.init (Cipher.encrypt_mode, key);//Initialize        byte[] result = Cipher.dofinal (bytecontent);returnResult//Encryption}Private Static byte[]Decrypt(byte[] content, String password)throwsNoSuchAlgorithmException, Nosuchpaddingexception, InvalidKeyException, Illegalblocksizeexception, badpaddingexception {Keygenerator KGen = keygenerator.getinstance ("AES"); Kgen.init ( -,NewSecureRandom (Password.getbytes ())); Secretkey Secretkey = Kgen.generatekey ();byte[] Encodeformat = secretkey.getencoded (); Secretkeyspec key =NewSecretkeyspec (Encodeformat,"AES"); Cipher Cipher = cipher.getinstance ("AES");//Create a cryptographic deviceCipher.init (Cipher.decrypt_mode, key);//Initialize         byte[] result = cipher.dofinal (content);returnResult//Encryption}Private StaticStringParsebyte2hexstr(byteBuf[]) {StringBuffer SB =NewStringBuffer (); for(inti =0; i < buf.length; i++) {String hex = integer.tohexstring (Buf[i] &0xFF);if(hex.length () = =1) {hex =' 0 '+ hex;          } sb.append (Hex.touppercase ()); }returnSb.tostring (); }Private Static byte[]Parsehexstr2byte(String hexstr) {if(Hexstr.length () <1)return NULL;byte[] result =New byte[Hexstr.length ()/2]; for(inti =0;i< hexstr.length ()/2; i++) {intHigh = Integer.parseint (Hexstr.substring (i*2, i*2+1), -);intLow = Integer.parseint (Hexstr.substring (i*2+1, i*2+2), -); Result[i] = (byte) (High * -+ low); }returnResult } Public StaticStringMD5(String s) {Try{MessageDigest m = messagedigest.getinstance ("MD5"); M.update (S.getbytes ("UTF-8"));byte[] Digest = M.digest (); BigInteger bigInt =NewBigInteger (1, digest);returnBigint.tostring ( -); }Catch(NoSuchAlgorithmException e) {Throw NewAssertionerror (); }Catch(Unsupportedencodingexception e) {Throw NewAssertionerror (); }    }}

Android: Cache server data for local storage

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.