Several post submission request modes for Android volley framework

Source: Internet
Author: User

First of all, a brief description of Google's Android development team launched in 2013, a network communication framework volley. It is designed to carry out a small amount of data, but frequent communication network operations, and for large data volume of network operations, such as downloading files, volley performance is not satisfactory.

In app development, the most common thing we do is send an HTTP request to the server from the app client. For two basic Web requests, get and post, get requests are relatively straightforward, Skip the table here. This article focuses on how several post submissions are made through volley.

1. The client submits a normal post, and the server returns a string

Requestqueue requestqueue = volley.newrequestqueue (Getapplicationcontext ()); Stringrequest stringrequest = new stringrequest (request.method.post,httpurl,     new Response.Listener<String> ()  {        @ Override        public void onresponse (String response) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D (TAG,  "response  ->  " + response);         }    },  new response.errorlistener ()  {         @Override          public void onerrorresponse (VolleyError error)  { &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (TAG, error.getMessage (),  error);    &nbsP;&NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&NBSP;&NBSP;&NBSP,})  {     @Override      protected map<string, string> getparams ()  {         //here to set parameters that require post                map<string, string> map = new hashmap<string, string > ();               map.put ("Name1",   "value1");               map.put (" Name2 ", " value2 ");            return  Params;    }};        requestqueue.add ( Stringrequest);

2. The client submits the JSON string as a POST request, and the server returns the JSON string

Requestqueue requestqueue = volley.newrequestqueue (Getapplicationcontext ()); Map<string, string> map = new hashmap<string, string> ();   Map.put ("name1",  "value1")   map.put ("name2",  "value2");  jsonobject  Jsonobject = new jsonobject (params); Jsonrequest<jsonobject> jsonrequest = new jsonobjectrequest (Method.POST,httpurl,  jsonObject,    new Response.Listener<JSONObject> ()  {          @Override         public void  onresponse (Jsonobject response)  {           &NBSP;&NBSP;LOG.D (tag,  "response -> "  + response.tostring ());         }    }, new response.errorlistener ()  {         @Override         public  void onerrorresponse (Volleyerror error)  {         &NBSP;&NBSP;&NBSP;&NBSP;LOG.E (Tag, error.getmessage (),  error);    }   &NBSP;&NBSP})     {    //Note the Getparams () method, which is the override here, Setting the post to be submitted at this point does not work at all     //must be the same as above, make up jsonobject as an argument into the Jsonobjectrequest object      //so this method is not needed here//     @Override//    protected map <string, string> getparams ()  {                 //          map <String, String> map = new HashMap<String, String> (  //);             map.put ("name1",  "value1");  //             map.put ("name2",  "value2");                   //         return params;//    }                  @Override     public Map<String,  String> getheaders ()  {        HashMap<String,  String> headers = new hashmap<string, string> ();         headers.put ("Accept",  "Application/json");         headers.put ("Content-type",  "Application/json; charset=utf-8");                         return headers;     }};requestqueue.add (jsonrequest);

Read the above code, will feel volley this framework is not perfect, using Jsonobjectrequest object to submit a POST request, if there are parameters need to commit, it must be submitted in Jsonobject JSON string.
If the server does not support this way? For example, the common spring MVC server, it is difficult to support the JSON request method.
then we want to achieve this goal, we need to use the method given below.

3. The client submits a normal post, and the server returns the JSON string
first in the activity class, inheriting the request implementation of a Normalpostrequest class

private class normalpostrequest extends request<jsonobject> {     private Map<String, String> mMap;    private Listener< Jsonobject> mlistener;    public normalpostrequest (String url,  Listener<jsonobject> listener,errorlistener errorlistener, map<string, string>  map)  {        super (request.method.post, url,  Errorlistener);                     mListener = listener;         Mmap = map;    }        //mmap is already following the way the previous , set the instance of the parameter      @Override     protected map<string, string > getparams ()  throws authfailureerror {        return mmap;     }        //here because the response return value requires JSON data, Like the Jsonobjectrequest class      @Override     protected Response< Jsonobject> parsenetworkresponse (Networkresponse response)  {         try {            string  jsonstring = new string (Response.data,httpheaderparser.parsecharset (response.headers));                              return response.success (New JSONObject ( jsonstring), Httpheaderparser.parsecacheheaders (response));         }  catch  (UNSUPPORTEDENCODINGEXCEPTION&NBsp;e)  {            return  Response.error (New parseerror (e));        } catch  ( Jsonexception je)  {            return  response.error (New parseerror (JE));        }     }     @Override     protected void deliverresponse (jsonobject response)  {        mlistener.onresponse (response );     }}

The

Next calls the same way as before, generating a request instance and joining the queue.

Requestqueue requestqueue = volley.newrequestqueue (Getapplicationcontext ()); Request<jsonobject> request = new normalpostrequest (httpurl,     New response.listener<jsonobject> ()  {         @Override         public void onresponse (JSONObject response) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.D (TAG,  "response  ->  " + response.tostring ());        }     }, new response.errorlistener ()  {        @ Override        public void onerrorresponse (VolleyError  error) &NBSP;{&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;LOG.E (TAG,  Error.getmessage (),  error);   &Nbsp;     }    }, params); Requestqueue.add (request); 

The above code is tested in the Android 4.3 environment.


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.