The project encapsulates network requests and adds a global cache mechanism.

Source: Internet
Author: User

The Caller class encapsulates Post and Get requests for both HttpURLConnection and HttpClient network access mechanisms, and adds the global cache mechanism. to use the cache mechanism, you must add the RequestCache class and initialize it in the onCreate method of the Application class of the project, and set it through the setRequestCache () method of Caller. example:

(PS: do not forget to add network permissions and register applications during the test; otherwise, no cache is available)

Caller class:

Package UK. AC. essex. httprequest. util; import Java. io. bufferedreader; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. outputstream; import java.net. httpurlconnection; import java.net. socketexception; import java.net. URL; import java.net. urlencoder; import Java. util. arraylist; import Java. util. hashmap; import Java. util. map; import Org. apache. HTTP. httpentity; Import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. client. clientprotocolexception; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. mess Age. basicnamevaluepair; import android. util. log; public class caller {Private Static final string tag = "Caller";/*** cache recently used requests */Private Static requestcache = NULL; public static void setrequestcache (requestcache) {caller. requestcache = requestcache ;} /*** use httpurlconnection to send a POST request ** @ Param urlpath * URL of the Service Request * @ Param Params * parameters in the Request Header * @ return * @ throws socketexcepti On * @ throws ioexception */public static string dopost (string urlpath, hashmap <string, string> Params) throws ioexception {string data = NULL; // obtain data from the cache first if (requestcache! = NULL) {DATA = requestcache. Get (urlpath); If (Data! = NULL) {log. I (TAG, "caller. dopost [cached] "+ urlpath); return data ;}/// no data in the cache, online data retrieval // complete Entity Data Assembly stringbuilder sb = new stringbuilder (); if (Params! = NULL &&! Params. isempty () {for (map. entry <string, string> entry: Params. entryset () {sb. append (entry. getkey ()). append ('='); sb. append (urlencoder. encode (entry. getvalue (), "UTF-8"); sb. append ('&');} sb. deletecharat (sb. length ()-1);} byte [] entity = sb. tostring (). getbytes (); // send the POST request httpurlconnection conn = NULL; Conn = (httpurlconnection) new URL (urlpath ). openconnection (); Conn. setconnecttimeout (5000); Conn. se Trequestmethod ("Post"); Conn. setdooutput (true); Conn. setrequestproperty ("Content-Type", "application/X-WWW-form-urlencoded"); Conn. setrequestproperty ("Content-Length", String. valueof (entity. length); outputstream outstream = Conn. getoutputstream (); outstream. write (entity); // return data if (Conn. getresponsecode () == 200) {DATA = convertstreamtostring (Conn. getinputstream (); If (requestcache! = NULL) {requestcache. put (urlpath, data); // write to the cache. You can use the cache mechanism} return data;} log by setting the caller requestcache object in the global application. I (TAG, "caller. dopost http: "+ urlpath); return data ;} /*** use httpclient to send a POST request ** @ Param urlpath * URL of the Request * @ Param Params * parameters in the Request Header * @ return * @ throws ioexception * @ throws clientprotocolexception * @ throws socketexception */public static string dopostclient (string urlpath, hashm AP <string, string> Params) throws ioexception {string data = NULL; // obtain data from the cache first if (requestcache! = NULL) {DATA = requestcache. Get (urlpath); If (Data! = NULL) {log. I (TAG, "caller. dopostclient [cached] "+ urlpath); return data ;}// no data in the cache, get data online // initialize httppost Request Header arraylist <namevaluepair> pairs = new arraylist <namevaluepair> (); If (Params! = NULL &&! Params. isempty () {for (map. entry <string, string> entry: Params. entryset () {pairs. add (New basicnamevaluepair (entry. getkey (), entry. getvalue () ;}} defaulthttpclient client = new defaulthttpclient (); httppost post = new httppost (urlpath); urlencodedformentity entity = NULL; httpresponse = NULL; try {entity = new urlencodedformentity (pairs, "UTF-8"); Post. setentity (entity); httpresponse = CLI Ent.exe cute (post); // response data if (httpresponse. getstatusline (). getstatuscode () == 200) {httpentity = httpresponse. getentity (); If (httpentity! = NULL) {inputstream = httpentity. getcontent (); Data = convertstreamtostring (inputstream); // cache data if (requestcache! = NULL) {requestcache. put (urlpath, data) ;}}} finally {client. getconnectionmanager (). shutdown ();} log. I (TAG, "caller. dopostclient http: "+ urlpath); return data ;} /*** use httpurlconnection to send a GET request ** @ Param urlpath * the URL of the Request * @ Param Params * parameters in the Request Header * @ return * @ throws ioexception */public static string doget (string urlpath, hashmap <string, string> Params) throws ioexception {string data = NULL ;// Obtain data from the cache first if (requestcache! = NULL) {DATA = requestcache. Get (urlpath); If (Data! = NULL) {log. I (TAG, "caller. doget [cached] "+ urlpath); return data ;}/// no data in the cache; get data online/package Request Header stringbuilder sb = new stringbuilder (urlpath ); if (Params! = NULL &&! Params. isempty () {sb. append ("? "); For (map. entry <string, string> entry: Params. entryset () {sb. append (entry. getkey ()). append ("="); sb. append (urlencoder. encode (entry. getvalue (), "UTF-8"); sb. append ("&");} sb. deletecharat (sb. length ()-1);} httpurlconnection conn = (httpurlconnection) new URL (sb. tostring ()). openconnection (); Conn. setconnecttimeout (5000); Conn. setrequestmethod ("get"); If (Conn. getresponsecode () == 200) {DATA = convertst Reamtostring (conn. getinputstream (); // cache data if (requestcache! = NULL) {requestcache. put (urlpath, data) ;}} log. I (TAG, "caller. doget http: "+ urlpath); return data ;} /*** use httpclient to send a GET request ** @ Param urlpath * the URL of the Request * @ Param Params * parameters in the Request Header * @ return * @ throws ioexception */public static string dogetclient (string urlpath, hashmap <string, string> Params) throws ioexception {string data = NULL; // obtain data from the cache first if (requestcache! = NULL) {DATA = requestcache. Get (urlpath); If (Data! = NULL) {log. I (TAG, "caller. dogetclient [cached] "+ urlpath); return data ;}/// no data in the cache; obtain data online // wrap the request header stringbuilder sb = new stringbuilder (urlpath ); if (Params! = NULL &&! Params. isempty () {sb. append ("? "); For (map. entry <string, string> entry: Params. entryset () {sb. append (entry. getkey ()). append ("="); sb. append (urlencoder. encode (entry. getvalue (), "UTF-8"); sb. append ("&");} sb. deletecharat (sb. length ()-1);} // instantiate the http get request object httpclient = new defaulthttpclient (); httpget = new httpget (sb. tostring (); httpresponse; try {// send the request httpresponse = httpclient.exe cute (httpget );/ /Receive data httpentity = httpresponse. getentity (); If (httpentity! = NULL) {inputstream = httpentity. getcontent (); Data = convertstreamtostring (inputstream); // cache data if (requestcache! = NULL) {requestcache. put (urlpath, data) ;}} finally {httpclient. getconnectionmanager (). shutdown ();} log. I (TAG, "caller. dogetclient http: "+ urlpath); return data;} Private Static string convertstreamtostring (inputstream is) {bufferedreader reader = new bufferedreader (New inputstreamreader (is )); stringbuilder sb = new stringbuilder (); string line = NULL; try {While (line = reader. readline ())! = NULL) {sb. append (LINE + "\ n") ;}} catch (ioexception e) {e. printstacktrace ();} finally {try {is. close ();} catch (ioexception e) {e. printstacktrace () ;}} return sb. tostring ();}}

RequestCache class:

Package uk. ac. essex. httprequest. util; import java. util. hashtable; import java. util. required list; public class RequestCache {// maximum number of caches private static int CACHE_LIMIT = 10; private reserved list <String> history; private Hashtable <String, String> cache; public RequestCache () {history = new history list <String> (); cache = new Hashtable <String, String> ();} public void put (String url, String data) {history. add (url); // if the maximum number of cached entries is exceeded, the earliest cached entry if (history. size ()> CACHE_LIMIT) {String old_url = (String) history. poll (); cache. remove (old_url);} cache. put (url, data);} public String get (String url) {return cache. get (url );}}

Project Application:

Package uk. ac. essex. httprequest; import uk. ac. essex. httprequest. util. caller; import uk. ac. essex. httprequest. util. requestCache; import android. app. application; public class DemoApplication extends Application {/*** global network request cache */private RequestCache mRequestCache; @ Overridepublic void onCreate () {super. onCreate (); mRequestCache = new RequestCache (); // initialize the cache Caller. setRequestCache (mRequestCache); // set cache for requests }}

Address: http://blog.csdn.net/hexingzhi/article/details/7425752

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.