Android's HTTP Operations Library volley basic use tutorial _android

Source: Internet
Author: User
Tags getmessage

Used to use Android library to do get, post, and so on the API to connect and operate.
But recently want to say look for the use of the library, should be able to do more with less.
I was looking for three sets of more people.
1.Android Asynchronous Http Client
2.okhttp
Square developed and open source, because before using their home Picasso, so to this set of fullness favor, but the use of the way is not very like
3.Volley
Volley was released by Google when Google I I/O in 2013, and has now accumulated a high popularity.
Volley's GitHub project address: Https://github.com/mcxiaoke/android-volley

Create a JSON request
volley comes with jsonobjectrequest and jsonarrayrequest to process JSON object requests and JSON data requests separately (but Voley does not write a Gson using the Gsonrequest library. Send a Request,volley directly to return a Java object, but we can write it ourselves.
Creates a JSON object request.
To send a request as simple as that, create a Jsonrequest object, write the response callback interface, and put the request in the request queue. Jsonarrayrequest is similar.

Tag used to cancel the request
String tag_json_obj = "Json_obj_req";
String url = "Http://api.androidhive.info/volley/person_object.json";

Jsonobjectrequest jsonobjreq = new Jsonobjectrequest (Method.get,url, NULL,
      new Response.listener<jsonobject > () {

        @Override public
        void Onresponse (jsonobject response) {
          log.d (TAG, response.tostring ());
        }
      , new Response.errorlistener () {

        @Override public
        void Onerrorresponse (volleyerror error) {
          VOLLEYLOG.D (TAG, "Error:" + error.getmessage ());
        }
      );

Adding request to request queue
appcontroller.getinstance (). Addtorequestqueue (Jsonobjreq, tag_json_obj);

Create a String request
stringrequest can be used to request any string type of data: Json,xml, text, and so on.

//Tag used to cancel the request String Tag_string_req = "String_req";

String url = "http://api.androidhive.info/volley/string_response.html";
ProgressDialog Pdialog = new ProgressDialog (this);
Pdialog.setmessage ("Loading ...");   

Pdialog.show (); 
        Stringrequest strreq = new Stringrequest (method.get, URL, new response.listener<string> () {@Override
          public void Onresponse (String response) {LOG.D (TAG, response.tostring ());

        Pdialog.hide ();
          }, New Response.errorlistener () {@Override public void Onerrorresponse (Volleyerror error) {
          VOLLEYLOG.D (TAG, "Error:" + error.getmessage ());
        Pdialog.hide ();

}
      });

Adding request to request queue Appcontroller.getinstance (). Addtorequestqueue (Strreq, tag_string_req); 

Creating a POST request
is all about get requests, and the following is a POST request, unlike a GET request, as long as the request type is changed to a POST request when the request is created, and the override The Getparams method of request can be.

Tag used to cancel the request String tag_json_obj = "Json_obj_req";
String url = "Http://api.androidhive.info/volley/person_object.json";
ProgressDialog Pdialog = new ProgressDialog (this);
Pdialog.setmessage ("Loading ...");   

  Pdialog.show (); Jsonobjectrequest jsonobjreq = new Jsonobjectrequest (method.post, URL, null, new Response.listener<jsonobje Ct> () {@Override public void Onresponse (Jsonobject response) {LOG.D (TAG, response.tostring
          ());
        Pdialog.hide ();
          }, New Response.errorlistener () {@Override public void Onerrorresponse (Volleyerror error) {
          VOLLEYLOG.D (TAG, "Error:" + error.getmessage ());
        Pdialog.hide ();  }} {@Override protected map<string, string> Getparams () {map<string, string> params =
      New hashmap<string, string> ();
      Params.put ("name", "androidhive");
  Params.put ("email", "abc@androidhive.info");    Params.put ("Password", "password123");
    return params;

}

  };

 Adding request to request queue Appcontroller.getinstance (). Addtorequestqueue (Jsonobjreq, tag_json_obj);

Add request header information

Tag used to cancel the request String tag_json_obj = "Json_obj_req";

String url = "Http://api.androidhive.info/volley/person_object.json";
ProgressDialog Pdialog = new ProgressDialog (this);
Pdialog.setmessage ("Loading ...");   

Pdialog.show (); Jsonobjectrequest jsonobjreq = new Jsonobjectrequest (Method.post,url, Null,new response.listener<jsonobject> ()
    {@Override public void Onresponse (Jsonobject response) {LOG.D (TAG, response.tostring ());
  Pdialog.hide (); }, New Response.errorlistener () {@Override public void Onerrorresponse (Volleyerror error) {VOLLEYLOG.D (TAG, "E
    Rror: "+ error.getmessage ());
  Pdialog.hide (); {/** * Passing some request headers * */@Override public map<string, String> Getheaders () throws
  Error {hashmap<string, string> headers = new hashmap<string, string> ();
  Headers.put ("Content-type", "Application/json");
  Headers.put ("Apikey", "xxxxxxxxxxxxxxx");
return headers;
}
}; AddingRequest to request queue Appcontroller.getinstance (). Addtorequestqueue (Jsonobjreq, tag_json_obj);

 

Create an image request
Volley library with Networkimageview class, this imageview can automatically use volley download pictures
1. Load pictures with Networkimageview
first, explain the principle of loading pictures:
Networkimageview loading the picture requires a imageloader and a picture URL, which requires a request queue object and a Imagecahe object. When you call the Networkimageview SetUrl method, you first determine whether the current ImageView URL is consistent with the new incoming URL, and if the same, you do not have to send the HTTP request again, if different, Then use the Imageloader object to send an HTTP request to get the picture.

Imageloader Imageloader = Appcontroller.getinstance (). Getimageloader ();
If you are using Networkimageview
imgnetworkview.setimageurl (Const.url_image, Imageloader);

Load a picture as simple as this ~ ~ ~
2. Use ImageView to load pictures
This process is similar to that of Networkimageview

Imageloader Imageloader = Appcontroller.getinstance (). Getimageloader ();

If you are using normal ImageView
imageloader.get (const.url_image, New Imagelistener () {

  @Override
  public void Onerrorresponse (Volleyerror error) {
    log.e (TAG, "Image Load Error:" + error.getmessage ());
  }

  @Override public
  void Onresponse (Imagecontainer response, Boolean arg1) {
    if (response.getbitmap ()!= null) { c10/>//load image into ImageView
      Imageview.setimagebitmap (Response.getbitmap ());}}
);

Can be a little more simple:

Loading image with placeholder and error image
Imageloader.get (Const.url_image, Imageloader.getimagelistener ( ImageView, r.drawable.ico_loading, R.drawable.ico_error));


A default Imagelistener has been written in the Imageloader.getimagelistener method.
Volley Cache
Volley has a powerful cache mechanism to manage request cache, which reduces the number of network requests and user latency.
To load a request from the request cache:

Cache cache = Appcontroller.getinstance (). Getrequestqueue (). GetCache ();
Entry Entry = cache.get (URL);
if (entry!= null) {
  try {
    string data = new String (Entry.data, "UTF-8");
    Handle data, like converting it to XML, JSON, bitmap etc.,
  } catch (Unsupportedencodingexception e) {   
    e.printst Acktrace ();}}
else{
  //Cached response doesn ' t exists. Make network call here
}

Invalidate the request cache
failure does not mean that the deletion, volley will continue to use the cached object until the new data is fetched from the server, and the new data will overwrite the old data.

Appcontroller.getinstance (). Getrequestqueue (). GetCache (). Invalidate (URL, true);

Close Cache
If you want to turn off the cache for one of the requests, call the request's Setshouldcache () method directly to:

String request
Stringrequest stringreq = new Stringrequest (...);

Disable Cache
Stringreq.setshouldcache (false);

Delete the cache of a URL
Call the cache Remove method to remove the cache for this URL:

Appcontroller.getinstance (). Getrequestqueue (). GetCache (). Remove (URL);

Remove all cache

Appcontroller.getinstance (). Getrequestqueue (). GetCache (). Clear ();

Cancel Request
when you add a request to the request queue, you can see that the addtorequestqueue (request, Tag) method also accepts a tag parameter, which is used to mark a type of request, so that all of the tag's requests can be canceled:

String Tag_json_arry = "Json_req";
Applicationcontroller.getinstance (). Getrequestqueue (). Cancelall ("Feed_request");

Request priority
when you create a request, you can override the request method's GetPriority method to return a priority divided into: Normal, Low, Immediate, and high.

Private Priority Priority = Priority.high;

Stringrequest strreq = new Stringrequest (Method.get,
      const.url_string_req, New response.listener<string> () {

        @Override public
        void Onresponse (String response) {
          log.d (TAG, response.tostring ());
          Msgresponse.settext (Response.tostring ());
          Hideprogressdialog ()}
      }, New Response.errorlistener () {

        @Override public
        void Onerrorresponse ( Volleyerror error) {
          volleylog.d (TAG, "error:" + error.getmessage ());
          Hideprogressdialog ();
        }
      }) {
    @Override public
    Priority getpriority () {return
      Priority;
    }

  };

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.