Use of Network Request library volley in Android app

Source: Internet
Author: User

Then, this time, how to use the volley, will give some examples, and the principle volley use Stringrequest
//Initializes a request queue, Requestqueue is the class of the volley libraryRequestqueue queue = Volley.newrequestqueue ( This); String URL= "Http://www.baidu.com";//define a string request queue, need to pass 4 parameters are: URL, the way of request (GET, post:), respond to the success of the processing function anonymous object, corresponding error when the processing function anonymous objectStringrequest stringrequest =Newstringrequest (Request.Method.GET, URL,NewResponse.listener<string>() {@Override Public voidOnresponse (String response) {//Display the first characters of the response string.Mtextview.settext ("Response is:" + response.substring (0,500)); }}, NewResponse.errorlistener () {@Override Public voidonerrorresponse (volleyerror error) {Mtextview.settext ("That didn ' t work!"); }});//added to the request queue, the network request is started by defaultQueue.add (stringrequest);

According to Volley's design rules, the program will simply create a requestqueue and pass a Request object line. Requestqueue maintains the running of some threads that are accessing the network, reads and writes the cache, and gets the return of network requests. The request object will be parsed after receiving the data, and Requestqueue will also be responsible for returning the parsed data to the main thread (UI thread) so that you can show the data in the UI control.

To use volley, you must declare Android.permission.INTERNET permissions in your app's Menifest file.

Process parsing of volley sending network

To get a requestqueue in your code, you can do so by default using the Volley.newrequestqueue method, as shown in the preceding code. Of course you can also define your own requestqueue. As you can see from the code above, when the request object is created, you simply call Requestqueue's Add () method (the parameter is the request object) to send the network request. When the Add method is called, volley will automatically create a cache processing thread and a network request thread pool, and volley will first determine if your sending network request has ever existed in the cache, and if it already exists, the cache processing thread will process the request and return the result (without any network interaction in the middle). If the network request that you send is not found in the cache, then this request is placed in the network request queue, the network request thread pool will get the request content from the network request queue, the network request transaction over HTTP, the returned result is returned by volley to the main thread.

Volley canceling a network request operation

The volley library can be done in code using the Cancelall () method in Requestqueue. For example, each request subclass has a settag (Object obj) method that sets each tag to a class of requests. For example, all of your request in an activity uses this (the activity's This is the activity instance) as the parameter of the Settag, you can call Requestqueue's cancelall anytime, anywhere (Object obj) method, passing this as an argument to obj so that all network requests for the activity are canceled. Of course, you can also pass arguments of any string type (preferably a meaningful string), code examples:

 Public Static Final String TAG = "MyTag"//  assume this exists. Requestqueue Mrequestqueue;  // assume this exists. // set tag for request to be divided Stringrequest.settag (TAG); Mrequestqueue.add (stringrequest);

The best way to cancel a network request is to place it in the activity's OnStop method (or anywhere, where it is customary), as follows

@Override protected void OnStop () {    super. OnStop ();     if NULL ) {        mrequestqueue.cancelall (TAG);    }}

It is also important to note that the response handler function for request (Response.listener and Response.errorlistener, see above) is not called at this time.

How to set the header of the HTPP request in requests, Body?

To set the header in HTTP requests in request, Boday content can overload the GetHeader method

Stringrequest request =NewStringrequest (Request.Method.POST, "www.yoururl.com",NewResponse.listener<string>() {@Override Public voidOnresponse (String s) {}},NewResponse.errorlistener () {@Override Public voidonerrorresponse (Volleyerror volleyerror) {}}) {@Override PublicMap<string, string> getheaders ()throwsAuthfailureerror {HashMap<string, string> map =NewHashmap<>(); Map<string, string> params =NewHashmap<string, string>(); Params.put ("User-agent", "Nintendo Gameboy"); Params.put ("Accept-language", "fr"); Params.put ("Authorization", "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b"); returnparams; }};

If it works for you, you can have a good one,:).

Use of Network Request library volley in Android app

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.