2

I am new to Volley and i'm trying to make Post request work with

JsonArrayRequest

From many answers I've found on stackoverflow, I tried as follows -

    private void getCounts() {
    String url = "http://192.168.1.100/json/count.php";
    JsonArrayRequest req = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    hidepDialog();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Log.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
            hidepDialog();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("LastUpdatedAt", "0");
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json; charset=utf-8");
            headers.put("User-agent", "My useragent");
            return headers;
        }

        @Override
        public byte[] getBody() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("LastUpdatedAt", "0");

            if (params != null && params.size() > 0) {
                Log.d(TAG, encodeParameters(params, getParamsEncoding()).toString());
                return encodeParameters(params, getParamsEncoding());
            }
            return null;
        }

        protected byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
            StringBuilder encodedParams = new StringBuilder();
            try {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                    encodedParams.append('=');
                    encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                    encodedParams.append('&');
                }
                return encodedParams.toString().getBytes(paramsEncoding);
            } catch (UnsupportedEncodingException uee) {
                throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
            }
        }

    };

    AppController.getInstance().addToRequestQueue(req);
}

As one can see, I have tried both, getParams() and getBody() to send LastUpdatedAt as Post request, but no matter what I try the value is not posted and returns null on server.

I even tried with using JsonArrayRequest(Request.Method.POST, ... and also by sending 'params' as JsonObject in the request, but even these two didn't work.

In one of the similar question, use of following class is suggested -

public class CustomJsonRequest extends Request {

Map<String, String> params;       
private Response.Listener listener; 

public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
                      Response.Listener responseListener, Response.ErrorListener errorListener) {

    super(requestMethod, url, errorListener);
    this.params = params;
    this.listener = responseListener;
}

@Override
protected void deliverResponse(Object response) {
    listener.onResponse(response); 

}

@Override
public Map<String, String> getParams() throws AuthFailureError {
         return params;
}

@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));
    }
}

}

But I couldn't make working Response listner createRequestSuccessListener and its error listener.

In the same similar question, following constructor is suggested -

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

But, I could not figure out how to make it work?

Community
  • 1
  • 1
Dr. Atul Tiwari
  • 1,085
  • 5
  • 22
  • 46
  • I couldn't understand where *exactly* your problem is. However, I also had several issues making POST requests using volley in the past. This answer solved my problem, maybe you could look at it and see whether it helps: http://stackoverflow.com/questions/19837820/volley-jsonobjectrequest-post-request-not-working/19945676#19945676 – tjiagoM May 06 '16 at 11:22

1 Answers1

2

Try to do something like:

        String url = "http://192.168.1.100/json/count.php";

        final JSONObject _jsonRequest = new JSONObject();
        _jsonRequest.put("key", value);

        JsonArrayRequest _stringRequest = new JsonArrayRequest(
         url , new Response.Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {

                // Your code here

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {

                // Your code here

            }

        }){

            @Override
            public byte[] getBody() {

                try {

                    return _jsonRequest.toString().getBytes(getParamsEncoding());

                } catch (UnsupportedEncodingException uee) {

                    return null;

                }

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {

                Map<String, String> _params = new HashMap<String, String>();

                _params.put("Content-type", "application/json");

                return _params;

            }

        };

        AppController.getInstance().addToRequestQueue(_stringRequest);
Lennon Spirlandelli
  • 3,131
  • 5
  • 26
  • 51
  • I tried, but it didn't work. There is some conflict with `JsonArrayRequest` and `Response.Listener`. So, if I try to put your code as such, it shows error. If I replace `String` with `JSONArray` at both places, it runs. but then throws error - `com.android.volley.ParseError: org.json.JSONException: Value You of type java.lang.String cannot be converted to JSONArray` – Dr. Atul Tiwari Apr 24 '15 at 22:36
  • Sorry I made a mistake. You should change `Response.Listener` to `Response.Listener`. Now the showed message error is because of what the server send back. It must be sending a `String` instead of `Array`. So in this case you have to use `StringRequest` instead of `JsonArrayRequest` and change `Response.Listener` to `Response.Listener` as well as `public void onResponse(JSONArray response)` to `public void onResponse(String response)` – Lennon Spirlandelli Apr 27 '15 at 12:54
  • Thanks for your reply. As I mentioned in my earlier comment, I corrected the `Response.Listner` to ``. And I think I found out, why now it's throwing `String can't be converted to JSONArray` error. Because my JsonObject is like - `_jsonRequest.put("LastUpdatedAt", "2015-03-15 00:30:04");` and this `LastUpdatedAt`, is received by my PHP code through `$_POST["LastUpdatedAt"]`, **which is not working in this case.** That's why my sql query is failing and returning error in string. So any thoughts on How to make it work? – Dr. Atul Tiwari Apr 28 '15 at 04:16
  • In continuation to my previous comment, I have also tried using `map` instead of `JsonObject` for my `Post` params, like this - `final Map _postContent = new HashMap();_postContent.put("LastUpdatedAt", "2015-03-15 00:30:04");` and tried using it at both places - `getBody()` and `getHeaders()`, but still my `$_POST['LastUpdatedAt']` is returning `null` – Dr. Atul Tiwari Apr 28 '15 at 04:43
  • You don't need to use `map`. `JsonObject` works well in that case. The problem could be because you send a `JsonObject` including the `LastUpdateAt` to server. So I think you should get the `JsonObject` in PHP instead of `$_post['LastUpdateAt']` – Lennon Spirlandelli Apr 28 '15 at 12:45
  • hanks. I got your point, but I don't know, how to receive JsonObject in PHP? I mean, I tried to receive it as - `$_POST['_jsonRequest']` and thought to decode json after receiving, but `$_POST['_jsonRequest']` also returned null. – Dr. Atul Tiwari Apr 28 '15 at 14:16
  • 1
    You can try this following questions: http://stackoverflow.com/questions/15994405/how-do-i-parse-a-json-object-in-php and http://stackoverflow.com/questions/25948191/send-post-request-using-volley-and-receive-in-php – Lennon Spirlandelli Apr 28 '15 at 15:12
  • I have moved to `$_GET`, but I am here to mention, that your 2nd link works. Although, heavy work in volley request is freezing my UI, and I have not found any solution for it, in last 7 days .. I think its time to ask another question – Dr. Atul Tiwari May 04 '15 at 09:46
  • Perhaps you should use a kinda `progressBar` to figure out that. So you start the progress while the `Volley` fetches data – Lennon Spirlandelli May 04 '15 at 14:35