Recently in the making of an Android news client, the feeling is quite rewarding.
Let's share some of the ways volley gets network data.
Volley is a network communication library launched by Google I/O 2013, which is highly scalable and uses it to make code more robust, and volley provides high-performance network communication capabilities while providing good support for network picture loading.
The following is mainly about the use of volley stringrequest
The simple notation is this:
1 /**2 * Get Network data News card3 */4 Private voidGetnewsdata (String newstype) {5String URL = Newstype;//Domestic News list6Stringrequest stringrequest =NewStringrequest (Request.Method.GET, URL,NewResponse.listener<string>() {7Gson Gson =NewGson ();8 9 @OverrideTen Public voidOnresponse (String response) { One //get the string sent over the network to do the operation, is generally converted to JSON and other operations A } -},NewResponse.errorlistener () { - the @Override - Public voidonerrorresponse (volleyerror error) { - //actions to be made when a request fails - } + }) { - +Mqueue.add (stringrequest);//join to the request queue, or the request will not be sent A Mqueue.start (); at}
Before committing the error of not writing add (), the middle Onresponse will not execute, hope warning
Here's how to add request parameters, such as Apikey Httparg, in volley
You need to override the Getheaders method:
1 @Override2 PublicMap<string, string> getheaders ()throwsAuthfailureerror3 {4map<string, string> headers =NewHashmap<string, string>();5Headers.put ("Charset", "UTF-8");6Headers.put ("Content-type", "Application/x-javascript");7Headers.put ("accept-encoding", "Gzip,deflate");8 returnheaders;9}
You can add any parameters you want in this area.
An example is given below:
1 /**2 * Get Network data News card3 */4 Private voidGetnewsdata (String newstype) {5String URL = Newstype;//Domestic News list6Stringrequest stringrequest =NewStringrequest (Request.Method.GET, URL,NewResponse.listener<string>() {7Gson Gson =NewGson ();8 9 @OverrideTen Public voidOnresponse (String response) { OneNewslistresponsejson Newslistjsonobject = Gson.fromjson (response, Newslistresponsejson.class); ANewsitems =Newslistjsonobject.getdata (); - } -},NewResponse.errorlistener () { the - @Override - Public voidonerrorresponse (volleyerror error) { - + } - }) { + @Override A PublicMap<string, string> getheaders ()throwsAuthfailureerror { atmap<string, string> headers =NewHashmap<>(); -Headers.put ("Apikey", constant.apiket); - returnheaders; - } - }; - Mqueue.add (stringrequest); in Mqueue.start (); -}
Note: (the picture is obtained through the Picasso, the use method please refer to the blogger's next article)
It's as simple as not to write threads, and all sorts of repetitive work, as usual.
:
Basic use of Android Volley/set HTTP request parameters, Apikey