One, the network request
Mobile software and app implementation mainly lies in the realization of local functional interaction and data presentation, and the data is often the core of mobile software. Data is often derived from
server, network data interaction plays a very important role.
Second, the network situation considerations
Network requests play an important role in data interactions. Because of the particularity of its process, there are many situations to be considered.
1, return value case
Interface crashes, returns an exception condition, and the interface correctly throws an exception back
The interface return content is empty, or the state is normal, the available data part is empty;
Interface normal return data, parse data error;
2, network request execution process
Before execution starts: Prompts the network request is executing, gives the user the good feedback, the shielding user's other operation "controls the malicious click, repeats submits"
During the execution: network request under certain conditions (return, Home, black screen, forced shutdown, phone, SMS insertion), need to do the network request to suspend, cancel, restart and other processing;
After execution: Parse the data, re-render the interface, especially when the network request error, need data echo and data reset, and give user-friendly prompt.
For the above scenario, you need to consider:
(1) Limit the network request header, can avoid repeated submissions, but also to achieve version control of the interface;
(2) The network request is best to achieve the queue effect, to be able to handle one of the network requests at the right time;
(3) Implement thread pool management, can not open threads indefinitely, control the current application of the consumption of the system;
(4) To achieve the data compression and encryption of network request, enhance the security of network request, reduce the amount of data, enhance the ability of information transmission and carrying.
Network requests primary interaction data types:
It is generally the interaction of a string with a picture file. Expand to forms, map data, files, and data streams as your app expands.
Iii. Open Source Framework
has been publicly used and the use of more effective network request methods mainly include: HttpClient, HttpURLConnection, Asynctask, Xutlis, Volley, OkHttp, Retrofit, android_async_ Http. From the initial network to the application framework to achieve encapsulation. Select the implementation to control.
HttpURLConnection:
public class Networkhttpconnection {/** * Timeout time */private static final int timeout_in_millions = 5000; /** * HttpURLConnection GET Request * Access path directly stitching full parameters * * @param urlstr Access Path * @return return content */public s Tatic string Doget (string urlstr) {URL url = null; HttpURLConnection conn = null; InputStream is = null; Bytearrayoutputstream BAOs = null; try {url = new URL (urlstr); conn = (httpurlconnection) url.openconnection (); Conn.setreadtimeout (timeout_in_millions); Conn.setconnecttimeout (timeout_in_millions); Conn.setrequestmethod ("GET"); Conn.setrequestproperty ("Accept", "*/*"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestproperty ("Content-type", "Application/json"); if (conn.getresponsecode () = =) {is = Conn.getinputstream (); BAOs = new Bytearrayoutputstream (); int len =-1; byte[] buf = new byte[128]; while (len = Is.read (BUF))! =-1) {baos.write (buf, 0, Len); } baos.flush (); return baos.tostring (); } else {throw new RuntimeException ("Responsecode is not 200 ... "); }} catch (Exception e) {e.printstacktrace (); } finally {try {if (is! = null) is.close (); } catch (IOException e) {e.printstacktrace (); } try {if (BAOs! = null) baos.close (); } catch (IOException e) {e.printstacktrace (); } if (conn! = null) {conn.disconnect (); }} return null; }/** * HttpURLConnection POST request * * @param URL to send request URL * @param param request parameter, request parameter should be nameThe form of 1=value1&name2=value2. * The response result of the remote resource represented by the @return */public static string DoPost (string url, string param) {printwriter out = null; BufferedReader in = null; String result = ""; try {URL realurl = new URL (URL); The connection between open and URL httpurlconnection conn = (httpurlconnection) realurl. OpenConnection (); Set the generic request attribute Conn.setrequestproperty ("accept", "*/*"); Conn.setrequestproperty ("Connection", "keep-alive"); Conn.setrequestmethod ("POST"); Conn.setrequestproperty ("Content-type", "Application/json"); Conn.setrequestproperty ("CharSet", "Utf-8"); Conn.setusecaches (FALSE); The Send POST request must be set to the following two lines conn.setdooutput (true); Conn.setdoinput (TRUE); Conn.setreadtimeout (timeout_in_millions); Conn.setconnecttimeout (timeout_in_millions); if (param! = null&&!param.trim (). Equals ("")) {//Gets the output stream corresponding to the URLConnection object out = new PrintWriter (conn . Getoutputstream ()); Send request parameter out.print (param); Flush output Stream Buffer Out.flush (); }//define BufferedReader input stream to read the response of the URL in = new BufferedReader (New InputStreamReader (Conn.getinputstream ( ))); String Line; while (line = In.readline ()) = null) {result + = line; }} catch (Exception e) {e.printstacktrace (); }//Use finally block to close the output stream, input stream finally {try {if (out! = null) {OU T.close (); } if (in = null) {in.close (); }} catch (IOException ex) {ex.printstacktrace (); }} return result; }}Volley:
* * Use volley package network request * Get/post can, call simultaneous in the external agreement * * @version V1.0 * @author: Vision * @date: 2016-06-22 13:38 */public class Networkvolley {public static Requestqueue Mqueue = Volley.newrequestqueue (Demoapplicatipn.getapplication ()); /** * POST Method Access Network * * @param method Access Path * @param params pass parameter * @param listener correct return Value Listener * @param errorlistener error when listener */public static void Networkbypost (String method, Jsonobject params, respon Se. Listener<jsonobject> Listener, Response.errorlistener errorlistener) {Js Onobjectrequest request = null; Request = new Jsonobjectrequest (Request.Method.POST, Method, params, listener, Errorlistener) { @Override public map<string, String> getheaders () throws Authfailureerror {Hashmap<str ing, string> headers = new hashmap<string, string> (); Headers.put ("User-agent", "representational meaningString string "); Headers.put ("Content-type", "x-www-form-urlencoded"); Headers.put ("accept-encoding", "gzip"); Headers.put ("Api-version", 1 + ""); return headers; } }; Request.setretrypolicy (New Defaultretrypolicy (15000,//set default time-out, 15 seconds defaultretrypolicy.default_max_retries,/ /default maximum number of attempts 1 defaultretrypolicy.default_backoff_mult)); Mqueue.add (Request); }/** * Get method Implements network request * * @param URL Access path * @param parames pass parameter * @param listener Correct return value Listener * @param errorlistener error when listener */public static void Networkbyget (String url, map<string, OBJECT&G T Parames, response.listener<jsonobject> Listener, Response.errorlistener errorlist Ener) {/** * stitching parameter */String PARAMSTR = ""; if (parames! = null) {for (String Key:parames.keySet ()) { PARAMSTR = paramstr + key + "=" + parames.get (key). ToString () + "&"; } URL = url + "?" + paramstr; /** * Execute Network Request */jsonobjectrequest request = new Jsonobjectrequest (Request.Method.GET, URL, NULL, Listener, Errorlistener) {@Override public map<string, String> getheaders () throws Aut Hfailureerror {hashmap<string, string> headers = new hashmap<string, string> (); Headers.put ("User-agent", "string string with meaning"); Headers.put ("Content-type", "x-www-form-urlencoded"); Headers.put ("accept-encoding", "gzip"); Headers.put ("Api-version", 1 + ""); return headers; } }; Request.setretrypolicy (New Defaultretrypolicy (15000,//set default timeout time, 15 seconds 0,//default maximum attempt 1.0f)); Mqueue.add (Request); }}Xutlis:
/** * @version V1.0 * @author: Vision * @date: 2016-06-22 14:33 */public class Networkxutils {/** * xutil request network data pos T * * @param URL * @param map * @param requestcallback */public static void Getjsonpostforxutil (St Ring URL, map<string, object> Map, requestcallback<string> requestcallback) {httputils HttpUtils = new Httputils (); Httputils.configtimeout (10000); Httputils.configsotimeout (10000); Httputils.configcurrenthttpcacheexpiry (1000); Requestparams params = new Requestparams (); For (map.entry<string, object> entry:map.entrySet ()) {Params.addbodyparameter (Entry.getkey (), entry.ge TValue (). toString ()); } httputils.send (HttpRequest.HttpMethod.POST, URL, params, requestcallback); }/** * Xutils request network data get * * @param URL * @param map * @param requestcallback */Public Stati c void getjsongetforxutil (String url, map<string, object> Map,Requestcallback<string> requestcallback) {httputils httputils = new Httputils (); String getUrl = ""; if (map! = null) {for (map.entry<string, object> entry:map.entrySet ()) {GETURL = Getur L + entry.getkey () + "=" + entry.getvalue () + "&"; } if (Geturl.length () > 1) {geturl.substring (0, Geturl.length ()-1); }} httputils.configcurrenthttpcacheexpiry (1000);//Network Request Httputils.send (Httprequest.httpmethod) to prevent continuous clicks. GET, url + getUrl, requestcallback); }}Gzip implementation class, call Gzipnetwork to implement network request "data compression"
public class Gziprequest extends Stringrequest {/** * uses the current constructor method, no parameter body, cannot use POST request * To use post, you need to override the Get parameter method GetParam S () * * @param method * @param URL * @param listener * @param errorlistener */Public Gzipreque St (int method, String URL, response.listener<string> Listener, Response.errorlistener Errorlistener) {super ( method, URL, listener, errorlistener); }/** * Default GET request * * @param URL * @param listener * @param errorlistener */Public gzipreques T (String URL, response.listener<string> Listener, Response.errorlistener Errorlistener) {super (URL, Listener , Errorlistener); }//Parse the gzip response using a gzipinputstream @Override protected response<string> Parsenetworkrespo NSE (networkresponse response) {/** * First to determine if data is gzip * "Access data using gzip mode, uncompressed data format does not accept" * * content-encoding Key Judgment field for whether the data return format is compressed */map<string, string> heAders = response.headers; if (headers! = null && headers.containskey ("content-encoding") && headers.get ("content-encoding"). Contains ("gzip")) {String output = ""; Note:better to use StringBuilder try {final Gzipinputstream gstream = new Gzipinputstream (n EW Bytearrayinputstream (response.data)); Final InputStreamReader reader = new InputStreamReader (gstream); Final BufferedReader in = new BufferedReader (reader); String Read; while (read = In.readline ()) = null) {output + = read; } reader.close (); In.close (); Gstream.close (); } catch (IOException e) {return response.error (new ParseError ()); } return response.success (output, Httpheaderparser.parsecacheheaders (Response)); } else {String output = null; try { Output = new String (Response.data, "utf-8"); } catch (Unsupportedencodingexception e) {e.printstacktrace (); } return response.success (output, Httpheaderparser.parsecacheheaders (Response)); }} @Override public map<string, String> getheaders () throws Authfailureerror {hashmap<string, S tring> headers = new hashmap<string, string> (); Headers.put ("User-agent", "meaningful string"); Headers.put ("Content-type", "application/x-www-form-urlencoded"); Headers.put ("accept-encoding", "gzip"); return headers; }}
public class Gzipnetwork {public static Requestqueue Mqueue = Volley.newrequestqueue (Demoapplicatipn.getapplication ()) ; /** * Get network request with gzip * * @param URL network request link address without parameters * @param params network request parameter * @param lis Tener Network request correct return value listener * @param errorlistener Network request error return value Listener */public static void Netgzipworkbyget (String URL, Map<string, string> params, response.listener<string> Listener, respons E.errorlistener errorlistener) {String paramstr = ""; if (params! = null) {for (String Key:params.keySet ()) {paramstr = paramstr + key + "=" + par Ams.get (Key) + "&"; } URL = url + "?" + paramstr; } gziprequest gziprequest = new Gziprequest (URL, Listener, errorlistener); Mqueue.add (gziprequest); }/** * Post network request with gzip * * @param URL network request link address without parameters * @param params network request parameter* @param listener Network request correct return value listener * @param errorlistener Network request error return value Listener */public static void Netgzipworkbypost (String URL, final map<string, string> params, response.listener<string> Listener, Response.errorlistener errorlistener) {gziprequest gziprequest = new Gziprequest (Request.Method.POST, URL, Listener, Errorlistener) {@Override protected map<string, string> Getparams () throws Au Thfailureerror {return params; } }; Mqueue.add (gziprequest); }} In the actual use of calls in the network class method can be, the Get/post method has been implemented, call parameter form consistent. The main is the get implementation after the link directly stitching parameters, can be seen from the outside, insecure and limited transmission of data; Post requests have their own request body, not displayed in the link, security is high, and the length of the data content is not limited.
Iv. Mutual relations
In the realization of httpurlconnection, the transfer of parameters is more troublesome, but the basic function is realized, and there is no efficiency consideration;
Xutlis Specialty lies in four modules: Dbutlis/viewutlis/httputlis/bitmaputlis.
Volley implementation of queue access is a relatively mature framework.
Volley+gzip, the network data compression is realized.
Click here to have a surprise $_$
once remember Xu, old Place, Pei Yu Ming xiao Song and dance; sword as ever, heart as before, 3,000 weak water prosperous road \ (^o^)/~
Android Basic Learning "historical process re-walk"----Network request (IV)