Xdroidrequest is a network request framework, and its functionality may be appropriate for you. This is the third edition of the project, the first two version because of the expansion of the problem has been not satisfied, thinking to think to go or think Google's volley is the strongest extension, so borrowed from the volley responsibility chain model, so with this third edition.
Provide
1 for Android 6.0, no longer use httpclient related API2 a line of code to send requests, provide a variety of callback functions to choose, 3 support 8 network request mode Get,post,put,delete,head,options,trace, PATCH4 support the priority setting of the request, priority will be lower than the priority of the sending request 5 to support the cancellation request, you can cancel the current sent request (can customize the conditions of the cancellation request), or cancel the request queue has not yet sent the request 6 to support multiple requests concurrent, multiple requests sent simultaneously, The underlying use of a fixed number of thread pools, you can set the size of the thread pool 7 support repeated request judgment, when a duplicate request will be suspended, waiting for the first request to complete, the pending request to use the cache has been completed, if the cache is not turned on, will continue to request Network 8 support request failed retry, default retry 2 times, The retry timeout is incremented, the increment rate can be set, the default is 1 time times increment 9 support multi-file and large file upload, can be sent to the server with parameters, provide upload progress callback 10 support large file download, provide download progress callback 11 support send JSON data 12 automatic network decision, You can set whether to display the cache data at this time 13 request results automatic parsing, can be generic any Java BEAN, the default implementation of Gson parsing, can customize more than 14 kinds of error types to determine 15 extensibility, customizable send request and parse request results 16 support powerful cache control 17 support cache configuration, Configurable disk cache path, disk cache maximum, disk cache current occupancy size, disk cache cleanup memory cache maximum size, memory cache cleanup 18 supports cache management and control, including local request caching a series of information queries and manual operation of the cache
About Cache
Here is the sample
Download demo.apk
Screenshot
Usage
1. Initialization, the application starts, the main initialization of the cache path and other information
Xrequest.initxrequest (Getapplicationcontext ());
2. Initiating the request
①get Request
/** * Simple GET request * @param mrequesttag request tag, can cancel request based on this tag * @param URL request address * @param onrequestlistener Request Result Callback */ xrequest.getinstance (). Sendget (Mrequesttag, URL, new onrequestlisteneradapter<string> () { @Override public void Ondone (request<?> Request, map<string, string> headers, String result, DataType DataType) { Super.ondone (request, headers, result, DataType); } });
②post Request
String url = "Http://apis.baidu.com/heweather/weather/free"; Requestparams params = new Requestparams ();p arams.putheaders ("Apikey", "can apply to Apistore");p arams.putparams ("City", " Hefei "); Xrequest.getinstance (). Sendpost (Mrequesttag, URL, params, new onrequestlisteneradapter<string> () {@Override public void onrequestfailed (request<?> request, HttpException HttpException) {super.onrequestfailed (Request, HttpException); Switch (Httpexception.gethttperrorcode ()) {case HttpError.ERROR_NOT_NETWORK:Toast.makeText (context, "net Not connected, please check ", Toast.length_short). Show (); Break }} @Override public void Onrequestretry (request<?> Request, int currentretrycount, HttpException previouse Rror) {Toast.maketext (context, "failed to get information, system has been retried for you" + currentretrycount+ "Times", Toast.length_short). Show (); CLOG.I ("Post request result failed, retrying, current retry count:" + currentretrycount); } @Override public void onrequestdownloadprogress (request<?> request, long transferredbytessize, long totalsize) {clog.i ("onrequestdownloadprogress current:%d, Total: %d ", transferredbytessize,totalsize); } @Override public void onrequestuploadprogress (request<?> Request, Long transferredbytessize, long totalsize, int Currentfileindex, File currentfile) {clog.i ("onrequestuploadprogress current:%d, Total:%d", tra Nsferredbytessize,totalsize); } @Override public void Ondone (request<?> Request, map<string, string> headers, String result, DataType DataType) {Super.ondone (Request, headers, result, dataType); }});
③ sending JSON string parameters
Requestparams params = new Requestparams ();p arams.putparams ( "{\" uid\ ": 863548,\" stickys\ ": [{\" id\ ": 29058,\" iid \ ": 0,\" content\ ": \" content \ ", \" color\ ": \" green\ ", \" createtime\ ": \" 2015-04-16 16:26:17\ ", \" updatetime\ ": \" 2015-04-16 16:26:17\ "}]}"); Xrequest.getinstance (). Sendpost (Mrequesttag, URL, params, new onrequestlisteneradapter<string> () { @ Override public void Ondone (request<?> Request, map<string, string> headers, String result, DataType DataType) { Super.ondone (request, headers, result, dataType); });
④ Uploading Files
String url = "http://192.168.1.150/upload_multi.php"; Requestparams params = new Requestparams ();p arams.put ("file[0]", New File (Environment.getexternalstoragedirectory (). GetAbsolutePath (), "app-debug.apk"));p Arams.put ("file[1]", New File (Environment.getexternalstoragedirectory (). GetAbsolutePath (), "photoview.apk"));p arams.putparams ("file_name", "uploaded file name"); Xrequest.getinstance (). Upload (Mrequesttag, url, params, new onrequestlisteneradapter<string> () {@Override PU Blic void Onrequestprepare (request<?> request) {Toast.maketext (context, "requesting preparation", Toast.length_short). Show (); CLOG.I ("request Preparation"); } @Override public void onrequestfailed (request<?> request,httpexception httpexception) {Toast.maketex T (context, "request result failed", Toast.length_short). Show (); CLOG.I ("Request result failed"); } @Override public void Onrequestretry (request<?> Request, int currentretrycount, HttpException previouserror) {Toast.maketext (context, "failed to get information, system has been retried for you")+ currentretrycount+ "Times", Toast.length_short). Show (); CLOG.I ("Request result failed, retrying, current retry count:" + currentretrycount); } @Override public void onrequestuploadprogress (request<?> Request, Long transferredbytessize, long totalsize, int Currentfileindex, file currentfile) {clog.i ("Uploading of%s files, current progress:%d, total size:%d", Currentfileindex,tran Sferredbytessize,totalsize); Muploadprogressbar.setmax ((int) totalsize); Muploadprogressbar.setprogress ((int) transferredbytessize); } @Override public void Ondone (request<?> Request, map<string, string> headers, String response, Datatyp E dataType) {Toast.maketext (context, "request Complete", Toast.length_short). Show (); }});
Test upload hundred megabytes or more files without pressure, if you want to test multi-file upload, the following PHP multi-file upload code for reference. Note that php default upload 2M within the file, you need to change the configuration file, many online, search can
<?php foreach ($_files[' file '] [' ERROR '] as $k = $v) { $uploadfile = './upload/'. basename ($_files[' file '] [' Name '] [$k]); if (move_uploaded_file ($_files[' file '] [' tmp_name '] [$k], $uploadfile) { echo "file:", $_files[' file '] [' Name '] [$k], "is valid, and was successfully uploaded.\n"; } else { echo "Possible file:", $_files[' file ' [' name '] [$k], "Upload attack!\n"; } } echo "Successfully received additional fields:". $_post[' file_name '];? >
⑤ Download File
String url = "http://192.168.1.150/upload/xiaokaxiu.apk"; String Downloadpath = "/sdcard/xrequest/download"; String fileName = "test.apk"; Xrequest.getinstance (). Download (Mrequesttag, URL, downloadpath,filename, new onrequestlisteneradapter<file> ( { @Override public void Onrequestdownloadprogress (request<?> Request, long transferredbytessize, long TotalSize) { clog.i ("Downloading, current progress:%d, total size:%d", transferredbytessize,totalsize); Mdownloadprogressbar.setmax ((int) totalsize); Mdownloadprogressbar.setprogress ((int) transferredbytessize); } @Override public void Ondone (request<?> Request, map<string, string> headers, File result, DataType DataType) { clog.i ("Download Complete:%s", Result! = Null?result.tostring (): "Get File Empty"); });
⑥ about callbacks
Request callback Onrequestlistener, a lot of callback functions, according to their own needs to selectively replicate, passed the Onrequestlistener default implementation class Onrequestlisteneradapter can be
Xrequest.getinstance (). Sendget (Mrequesttag, URL, CacheKey, params, new onrequestlistener<string> () {/** * Prepare callback before request * Run Thread: Main thread * @param request Current Requested Object */@Override public void Onrequestprepare (request<?> request) {Toast.maketext (context, "GET request Preparation", Toast.len Gth_short). Show (); CLOG.I ("Get request Preparation"); }/** * Request completion callback * Run Thread: Main thread * @param request current Requested Object * @param head ERs request result header file Map collection * @param result request Results Generic Object */@Override public void ONrequest Finish (request<?> Request, map<string, string> headers, String result) {Toast.maketext (context , "GET request results get successful", Toast.length_short). Show (); CLOG.I ("Get successful results"); /** * Request failed callback * Run Thread: Main thread * @param request current Requested Object * @param httpexception Error class object containing error code and error description */@Override public void onrequestfailed (request& lt;? > Request, HttpException httpexception) {toast.maketext (context, "Get request result failed", Toast.length_short). Show ( ); CLOG.I ("Get request result failed"); /** * Request Failed retry callback * Run Thread: Main thread * @param request current Requested Object * @param cu Rrentretrycount Current Retries * @param previouserror An error class object containing the error code and description of the error */@Override public void Onrequestretry (request<?> Request, int currentretrycount, HttpException previouserror) { Toast.maketext (Context, "Get information failed, system already retries for you" + currentretrycount+ "Times", Toast.length_short). Show (); CLOG.I ("Get request result failed, retrying, current retry count:" + currentretrycount); /** * Download Progress callback * Run Thread: Child thread * @param request current Requested Object * @param Tran Sferredbytessize Current Download size* @param totalsize Total size * */@Override public void onrequestdownloadprogress (Request<?> Request, Long transferredbytessize, long totalsize) {clog.i ("onrequestdownloadprogress current:%d, Total:%d", transferredbytessize,totalsize); }/** * Upload progress callback * Run Thread: Child thread * @param request current Requested Object * @param Tran Sferredbytessize Current Write Progress * @param totalsize Total Progress * @param Currentfileindex is currently uploading the first few files * * * * @param currentfile The file object currently being uploaded * */@Override public void Onrequestuploa Dprogress (request<?> Request, Long transferredbytessize, long totalsize, int currentfileindex, Fi Le Currentfile) {clog.i ("onrequestuploadprogress current:%d, Total:%d", transferredbytessize,totalsize) ; }/** * Cache data Load Complete callback * Running thread: main thread * @param request current Requested Object * @param headers cache header Information Map collection * @param result cached Data Results object */@Override public void Oncachedataloadfinish (request<?> Request, map<string, String > headers, String result) {Toast.maketext (context, "GET request Cache loaded successfully", Toast.length_short). Show (); CLOG.I ("GET Request Cache loaded successfully"); /** * Parse the network data callback, after the request is completed, if you need to do time-consuming operations (such as writing to the database) can be done in this callback, do not block the UI * Running threads: Child threads * @para M requests the current request object * @param networkresponse Network Request result object, containing byte data stream and header information, etc. * @param result parsing the object constructed by the byte data stream */@Override public void Onparsenetworkresponse (request<?> Request, Networkresponse Networkresponse, String result) {clog.i ("GET Request network data parsing complete"); }/** * This request eventually completes the callback, and each request is only called once, regardless of whether the request goes to the cached data or the network data, and the result of the last delivery goes this callback * running thread: main thread * @pa RAM request currently requested object * @param headers Final Delivery data header information * @param result final Delivery Request Results Object * @param dataType Final Deliverable Data type enumeration, net Network data/Cache data */@Override public void Ondone (request<?> Request, map<string, String > headers, String result, DataType DataType) {toast.maketext (context, "GET request Complete", toast.length_short). Sh ow (); } });
The following is a selective replication callback function
String url = "Http://apis.baidu.com/heweather/weather/free"; Requestparams params = new Requestparams (); Params.putheaders ("Apikey", "can apply to Apistore"); Params.putparams ("City", "Hefei"); String CacheKey = URL + "POST"; As with GET request URL, in order to avoid the same cache key, here re-specify Cache key Xrequest.getinstance (). Sendpost (Mrequesttag, URL, CacheKey, params, new OnR Equestlisteneradapter<string> () {@Override public void onrequestfailed (request<?> reque St, HttpException HttpException) {super.onrequestfailed (request, HttpException); Switch (Httpexception.gethttperrorcode ()) {case HttpError.ERROR_NOT_NETWORK:Toast.make Text (context, "Network not connected, please check", Toast.length_short). Show (); Break }} @Override public void Onrequestretry (request<?> Request, int currentretrycount, HttpException previouserror) {Toast.makeText (Context, "Get information failed, system already retries for you" + currentretrycount+ "Times", Toast.length_short). Show (); CLOG.I ("Post request result failed, retrying, current retry count:" + currentretrycount); } @Override public void onrequestdownloadprogress (request<?> Request, Long Transferredbytessiz E, long TotalSize) {clog.i ("onrequestdownloadprogress current:%d, Total:%d", transferredbytessize,total Size); } @Override public void onrequestuploadprogress (request<?> Request, Long transferredbytessize, Long totalsize, int currentfileindex, File currentfile) {clog.i ("Onrequestuploadprogre SS current:%d, Total:%d ", transferredbytessize,totalsize); } @Override public void Ondone (request<?> Request, map<string, string> headers, String R Esult, DataType DataType) {super.ondone (Request, headers, result, DataType); } }); }
⑦ Automatic parsing
String url = "Http://apis.baidu.com/apistore/aqiservice/citylist"; Requestparams params = new Requestparams ();p arams.putheaders ("Apikey", "can apply to Apistore"); Xrequest.getinstance (). Sendpost (Mrequesttag, URL, params, cityrootbean.class, new onrequestlisteneradapter< Cityrootbean<citybean>> () { @Override public void Ondone (request<?> Request, map<string, string> headers, cityrootbean<citybean> result, DataType DataType) { clog.i ("Bean Info:" + (Result = = Null? "Null": Result.tostring ()));} );
⑧ Cache Configuration
(1) When initializing, if you want to specify the cache path, size and other information, you can refer to the following code
public class App extends application { @Override public void OnCreate () { super.oncreate (); Configxreqeustcache (); } @SuppressLint ("Sdcardpath") private void Configxreqeustcache () { //disk cache path File Disk_cache_dir_path = new File ("/sdcard/xrequest/diskcache"); Disk cache maximum value int disk_cache_max_size = 30*1024*1024; Xrequest.initxrequest (Getapplicationcontext ()); Xrequest.initxrequest (Getapplicationcontext (), disk_cache_max_size, Disk_cache_dir_path);} }
(2) Find the space occupied by the current cache data
Long diskcachecurrentsize = Requestcachemanager.getinstance (). Getalldiskcachesize ();
(3) Finding the cache path
String Diskcachedir = Requestcachemanager.getinstance (). Getdiskcachedirectory (). GetPath ();
(4) Query the current cache maximum value
Long diskcachemaxsize = Requestcachemanager.getinstance (). Getdiskcachemaxsize ();
(5) Clear all caches
Requestcachemanager.getinstance (). Deletealldiskcachedata ();
⑨ Request Configuration
At the time of sending the request, some overloaded functions need to pass in an Requestcacheconfig object, and the default Requestcacheconfig object is passed inside the overloaded function that does not need to pass in this object. The Requestcacheconfig object control is cached on the network data, and the following is the default Requestcacheconfig configuration
public static Requestcacheconfig Builddefaultcacheconfig () {requestcacheconfig cacheconfig=new requestcacheconfig (); Cacheconfig.setshouldcache (true); Turn on cache Cacheconfig.setusecachedataanyway (false); Shutdown always takes precedence over cache cacheconfig.setusecachedatawhenrequestfailed (true);//Open request failed using cache Cacheconfig.setusecachedatawhentimeout (FALSE); Shutdown timeout using cache cacheconfig.setusecachedatawhenunexpired (true); Turn on cache cacheconfig.setretrywhenrequestfailed when cache is not expired (true);//Open request failed retry cacheconfig.setneverexpired ( FALSE); Close cache never expires Timecontroller timecontroller=new Timecontroller (); Timecontroller.setexpirationtime (Default_expiration_time); Sets the expiration time of the cache timecontroller.settimeout (default_timeout);//Set cache time-out time, corresponding to the "setusecachedatawhentimeout" function time-out Cacheconfig.settimecontroller (Timecontroller);//Set the time controller to Requestcacheconfig return cacheconfig;}
For each request, if you need to reassign the configuration, you can construct such an object to pass in
⑩ Raw Send Request mode
Xrequest is actually using decorator mode to encapsulate a series of request steps to make it easier to use, and if there are complex requirements that require higher degrees of freedom, you can refer to the following send request code
multipartgsonrequest<bean> request = new multipartgsonrequest<t> (cacheconfig, URL, CacheKey, Bean.class, Onrequestlistener); Request.setrequestparams (params); Request.sethttpmethod (httpmethod.post); Request.setTag (TAG) ; Xrequest.getinstance (). Addtorequestqueue (Request);
Xdroidrequest Network Request framework, new Open source