An example tutorial on using the Volley library to send HTTP requests in Android development _android

Source: Internet
Author: User
Tags stub git clone

Android volley is a Google-developed network Lib that makes it easier and faster for you to access network data. The volley library's network requests are asynchronous, and you don't have to worry about asynchronous processing problems.
Advantages of Volley:

    • Request queue and Request priority
    • Request cache and memory management
    • Strong scalability
    • can cancel request

Download and compile Volley.jar
need to install Git,ant,android SDK
Clone code:

git clone Https://android.googlesource.com/platform/frameworks/volley

Compile jar:

Android Update project-p. Ant Jar

Add Volley.jar to your project
But someone has put the volley code on the GitHub:
Https://github.com/mcxiaoke/android-volley, you can use volley in a simpler way:
Maven
Format:jar

<dependency>
  <groupId>com.mcxiaoke.volley</groupId>
  <artifactid>library</ artifactid>
  <version>1.0.6</version>
</dependency>

Gradle
Format:jar

Compile ' com.mcxiaoke.volley:library:1.0.6 '

Volley working principle diagram

Create a volley single example
when using volley, you must create a request queue Requestqueue, the best way to use the request queue is to make it a single case, and the entire app uses such a request queue.

public class AppController extends application {public static final String TAG = Appcontroller.class. Getsimplename

();
Private Requestqueue Mrequestqueue;

Private Imageloader Mimageloader;

private static AppController minstance;
  @Override public void OnCreate () {super.oncreate ();
Minstance = this;

public static synchronized AppController getinstance () {return minstance;} Public Requestqueue Getrequestqueue () {if (Mrequestqueue = null) {Mrequestqueue = Volley.newrequestqueue (getAppli
  Cationcontext ());
return mrequestqueue;
  Public Imageloader Getimageloader () {getrequestqueue ();
  if (Mimageloader = = null) {Mimageloader = new Imageloader (This.mrequestqueue, New Lrubitmapcache ());
return this.mimageloader;
  } public <T> void Addtorequestqueue (request<t> req, String tag) {//Set the default tag if tag is empty Req.settag (Textutils.isempty (tag)?
  Tag:tag);
Getrequestqueue (). Add (req); } public <T> void Addtorequestqueue (request<t> req) {Req.settag (TAG);
Getrequestqueue (). Add (req);
  public void cancelpendingrequests (Object tag) {if (mrequestqueue!= null) {Mrequestqueue.cancelall (tag);

 }
}
}

In addition, you will need a cache to store the requested picture:

public class Lrubitmapcache extends Lrucache<string, bitmap> implement Imagecache {public
  static int Getdefaul Tlrucachesize () {
    final int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);
    Final int cacheSize = MAXMEMORY/8;

    return cacheSize;
  }

  Public Lrubitmapcache () {This
    (getdefaultlrucachesize ());
  }

  Public Lrubitmapcache (int sizeinkilobytes) {
    super (sizeinkilobytes);
  }

  @Override
  protected int sizeOf (String key, Bitmap value) {return
    value.getrowbytes () * Value.getheight ()/102 4;
  }

  @Override public
  Bitmap getbitmap (String URL) {return get
    (URL);
  }

  @Override public
  void putbitmap (String url, Bitmap Bitmap) {put
    (URL, Bitmap);
  }
}

Don't forget to add Android.permission.INTERNET permissions to the Androidmanifest.xml file.

HTTP request Instance

  Private context Mcontext;
  Private Requestqueue Mrequestqueue;

  Private Stringrequest mstringrequest;
    Using volley to implement POST request private void Volley_post () {String URL = "Http://aplesson.com/wap/api/user.php?action=login";
    Mcontext = this;
    Mrequestqueue = Volley.newrequestqueue (Mcontext);
          Mstringrequest = new Stringrequest (method.post, URL, new response.listener<string> () {@Override
          public void Onresponse (String response) {System.out.println ("request Result:" + response); 
            }, New Response.errorlistener () {@Override public void Onerrorresponse (Volleyerror error) {
          SYSTEM.OUT.PRINTLN ("Request error:" + error.tostring ()); }} {//Carry parameters @Override protected hashmap<string, string> Getparams () throws Au
        Thfailureerror {hashmap<string, string> HashMap = new hashmap<string, string> (); Hashmap.put ("un", "852041173");
        Hashmap.put ("PW", "852041173abc");
      return HASHMAP; The//Volley request class provides a getheaders () method that overloads this method to customize HTTP header information. (also not implemented) public map<string, String> getheaders () throws Authfailureerror {hashmap<string, String&gt ;
        headers = new hashmap<string, string> ();
        Headers.put ("Accept", "Application/json"); Headers.put ("Content-type", "Application/json;
        Charset=utf-8 ");
      return headers;

    }

    };

  Mrequestqueue.add (mstringrequest);

  Private Jsonobjectrequest mjsonobjectrequest;
    Using volley to implement JSON data request private void Volley_json () {mcontext = this;
    String url = "http://aplesson.com/data/101010100.html";
    1 Create requestqueue Object mrequestqueue = Volley.newrequestqueue (Mcontext); 2 Create jsonobjectrequest Object mjsonobjectrequest = new Jsonobjectrequest (URL, null, new Response.listener<json Object> () {@Override public void Onresponse (Jsonobject response) {
            SYSTEM.OUT.PRINTLN ("Request Result:" + response.tostring ()); 
            }, New Response.errorlistener () {@Override public void Onerrorresponse (Volleyerror error) {
          SYSTEM.OUT.PRINTLN ("Request error:" + error.tostring ());

    }
        });

  3 Add Jsonobjectrequest to Requestqueue Mrequestqueue.add (mjsonobjectrequest);
    ////using volley to implement GET request private void Volley_get () {mcontext = this;
    String url = "http://www.aplesson.com/";
    1 Create requestqueue Object mrequestqueue = Volley.newrequestqueue (Mcontext);
          2 Create stringrequest Object mstringrequest = new Stringrequest (URL, new response.listener<string> () {
          @Override public void Onresponse (String response) {System.out.println ("request Result:" + response); The new Response.errorlistener () {@Override public void Onerrorresponse (Volleyerror er ROR) {System.out.println ("Request error:" + Error.tostriNg ());
    }
        });
  3 Add Stringrequest to Requestqueue Mrequestqueue.add (mstringrequest);

 }


Volley provides jsonobjectrequest, Jsonarrayrequest, Stringrequest and other request forms. Jsonobjectrequest: Returns the JSON object.
Jsonarrayrequest: Return to Jsonarray.
Stringrequest: Returns a string so that you can handle the data yourself more flexibly.
You can also inherit from request<t> custom request.

Cancel Request
activity inside launched the network request, and in this network request has not returned the result, the activity was ended, at this time if continue to use the context, and so on, in addition to the innocent waste of CPU, batteries, networks and other resources, may also lead to program crash, So, we need to deal with this situation. With volley, we can cancel all or some of the incomplete network requests while the activity stops. All the request results in the volley are returned to the main process, and if certain requests are canceled in the main process, the requests are not returned to the main thread. Volley supports a variety of request cancellation methods.
You can cancel an operation for some request:

 @Override public
  void OnStop () {for
    (Request <?> req:mrequestqueue) {
      req.cancel ()
  }}

Cancel all requests in this queue:

 @Override
  protected void OnStop () {
    //TODO auto-generated method Stub
    super.onstop ();
    Mrequestqueue.cancelall (this);
  }

Can terminate certain requests according to Requestfilter or tag

 @Override
  protected void OnStop () {
    //TODO auto-generated method Stub
    super.onstop ();

    Mrequestqueue.cancelall (New Requestfilter () {});
    or
    Mrequestqueue.cancelall (new Object ());
  }

Volley supports HTTP GET, POST, put, delete, and other methods.


Related Article

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.