Several post request methods of the Android Volley framework

Source: Internet
Author: User

Several post request methods of the Android Volley framework
First, let's briefly describe Volley, a network communication framework launched by Google's Android development team in 2013. its design goal is to perform network operations with a small amount of data but frequent communication, and Volley's performance is not satisfactory for network operations with a large amount of data, such as downloading files.

In app development, we send an http request from the app client to the server. for the two basic web request methods get and post, the get request method is relatively simple and is skipped here. this article focuses on several post submission methods through volley.

1. The client submits the request in normal post mode, and the server returns the string

RequestQueue requestQueue = Volley. newRequestQueue (getApplicationContext (); StringRequest stringRequest = new StringRequest (Request. Method. POST, httpurl, new Response. Listener
 
  
() {@ Override public void onResponse (String response) {Log. d (TAG, "response->" + response) ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {Log. e (TAG, error. getMessage (), error) ;}}) {@ Override protected Map
  
   
GetParams () {// set the Map parameter for post here
   
    
Map = new HashMap
    
     
(); Map. put ("name1", "value1"); map. put ("name2", "value2"); return params ;}}; requestQueue. add (stringRequest );
    
   
  
 
2. The client submits the request in the form of a json string post request, and the server returns the json string

RequestQueue requestQueue = Volley. newRequestQueue (getApplicationContext (); Map
 
  
Map = new HashMap
  
   
(); Map. put ("name1", "value1"); map. put ("name2", "value2"); JSONObject jsonObject = new JSONObject (params); JsonRequest
   
    
JsonRequest = new JsonObjectRequest (Method. POST, httpurl, jsonObject, new Response. Listener
    
     
() {@ Override public void onResponse (JSONObject response) {Log. d (TAG, "response->" + response. toString () ;}}, new Response. errorListener () {@ Override public void onErrorResponse (VolleyError error) {Log. e (TAG, error. getMessage (), error) ;}}) {// note the getParams () method of override here. Setting parameters to be submitted by post does not work at all. // it must be the same as above, construct a JSONObject and pass it into the JsonObjectRequest object as a real parameter. // This method is not required here. // @ Override // protected Map
     
      
GetParams () {// Map
      
        Map = new HashMap
       
         (); // Map. put ("name1", "value1"); // map. put ("name2", "value2"); // return params; //} @ Override public Map
        
          GetHeaders () {HashMap
         
           Headers = new HashMap
          
            (); Headers. put ("Accept", "application/json"); headers. put ("Content-Type", "application/json; charset = UTF-8"); return headers ;}}; requestQueue. add (jsonRequest );
          
         
        
       
      
     
    
   
  
 
After reading the above code, I think the volley framework is not perfect enough. I use the JsonObjectRequest object to submit a post request. If any parameter needs to be submitted, I must submit it in the json string of JSONObject.
What if the server does not support this method? For example, the common spring mvc server is difficult to support json request methods.
To achieve this goal, we need to use the following methods.

3. The client submits the request in normal post mode, and the server returns a json string.
First, in the Activity class, inherit the Request to implement a NormalPostRequest class
Private class NormalPostRequest extends Request
 
  
{Private Map
  
   
MMap; private Listener
   
    
MListener; public NormalPostRequest (String url, Listener
    
     
Listener, ErrorListener errorListener, Map
     
      
Map) {super (Request. method. POST, url, errorListener); mListener = listener; mMap = map;} // mMap has already set the parameter instance @ Override protected Map in the preceding way.
      
        GetParams () throws AuthFailureError {return mMap;} // json data is required because the returned value of response is the same as that of JsonObjectRequest. @ Override protected Response
       
         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 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 call method is similar to the previous one. Generate a Request instance and add it to the queue.
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());Request
 
   request = new NormalPostRequest(httpurl,    new Response.Listener
  
   () {        @Override        public void onResponse(JSONObject response) {            Log.d(TAG, "response -> " + response.toString());        }    }, new Response.ErrorListener() {        @Override        public void onErrorResponse(VolleyError error) {            Log.e(TAG, error.getMessage(), error);        }    }, params);requestQueue.add(request);
  
 
The above code is successfully tested in the android 4.3 environment.

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.