Send a JSONArray POST request with android volley library
Asked Answered
M

4

3

I would like to send and receive a Json Array with volley. Now I can receive an array and it's ok but I don't know how to send a request (For example: with post method).

JsonArrayRequest arrayReq = new JsonArrayRequest(URL,
            new Listener<JSONArray>() {
}
Modigliani answered 22/2, 2015 at 10:35 Comment(0)
S
2
 List<Map<String,String>> listMap =  new ArrayList<Map<String, String>>();
        Map<String,String> map  = new HashMap<String,String>();
        try {

            map.put("email", customer.getEmail());
            map.put("password",customer.getPassword());

        } catch (Exception e) {
            e.printStackTrace();
        }
        listMap.add(map);

        String url = PersonalConstants.BASE_URL+"/url";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
                Request.Method.POST, url, String.valueOf(new JSONArray(listMap)),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        Log.d(App.TAG, jsonObject.toString());
                    }
                }, new Response.ErrorListener (){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d(App.TAG,volleyError.toString());
            }
        }
        );
        App.getInstance().getmRequestQueue().add(jsonObjectRequest);
Stellarator answered 30/4, 2015 at 15:0 Comment(0)
F
1

Here is an example:

// Define the web service URL
final String URL = "http://www.someurl.com";

// POST params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "raha tamjid");

// Define the POST request
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
   new Response.Listener<JSONObject>() {
       @Override
       public void onResponse(JSONObject response) {
           try {
               VolleyLog.v("Response:%n %s", response.toString(4));
           } catch (JSONException e) {
               e.printStackTrace();
           }
       }
   }, new Response.ErrorListener() {
       @Override
       public void onErrorResponse(VolleyError error) {
           VolleyLog.e("Error: ", error.getMessage());
       }
   });

// Add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

How the POST request differs is that it takes a JSONObject as parameter.

EDIT 1:

If you have Volley installed as a library project in your IDE, then just define a new constructor

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
    Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener);
}

inside the class JsonArrayRequest which is present in the Volley library code. Now you can use this to create JsonArrayRequest objects and add them to the RequestQueue.

EDIT 2:

1. Get the Volley library project from here. Download the project and set it up in your IDE.

2. Make the modification to the JsonRequest class (found in com.android.volley.toolbox namespace) as discussed in EDIT 1.

3. Delete the volley.jar from the libs folder of your APPLICATION PROJECT.

4. Now go to Project Properties -> Android -> Library and click on Add. From here select the Volley project. Clean & Rebuild.

5. Now in your APPLICATION PROJECT you can make a POST JsonArrayRequest just like how we make a POST JsonObjectRequest and get a JSONArray in the Response.

Flier answered 22/2, 2015 at 10:44 Comment(2)
thank you . but i want to get Json Array in response not Json Object .Modigliani
no . i have the volley 's .jar file . how to do that can you show me ?thanksModigliani
R
0

Create a class and extend JsonArrayRequest then override

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("name", "value");
    return params;
}

and add a new constructor and in it call

super(Method.POST, url, null, listener, errorListener);

or use this class

public class PostJsonArrayRequest extends JsonRequest<JSONArray> {

    /**
     * Creates a new request.
     * @param url URL to fetch the JSON from
     * @param listener Listener to receive the JSON response
     * @param errorListener Error listener, or null to ignore errors.
     */
    public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
        super(Method.POST, url, null, listener, errorListener);
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("name", "value");
        return params;
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString =
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }
}
Ritchie answered 29/6, 2015 at 10:13 Comment(0)
J
0

Create a new java class named JsonArrayPostRequest now you can use it like the previous request, just replace JSONArrayRequest with JsonArrayPostRequest and pass the correct parameters

public  class JsonArrayPostRequest extends Request<JSONArray>{  
    private Map<String,String> mParam;  
    private Listener<JSONArray>  mListener;  


    public JsonArrayPostRequest(String url,Listener<JSONArray> listener, ErrorListener errorListener,Map param) {  
        super(Request.Method.POST, url, errorListener);  
        mListener=listener;  
        mParam=param;   
    }  
    @Override  
    protected Map<String, String> getParams() throws AuthFailureError {  
        return mParam;  
    }  

       @Override  
        protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {  
            try {  
                String jsonString =  
                    new String(response.data, HttpHeaderParser.parseCharset(response.headers));  
                return Response.success(new JSONArray(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(JSONArray response) {  
        mListener.onResponse(response);  

    }  

} 

USE:

JsonArrayPostRequest request = new JsonArrayPostRequest(URL,new Response.Listener<JSONArray>(),             
                new Response.ErrorListener() ,params);
Jellify answered 27/9, 2017 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.