3

I have the code below (Volley Library By Google) to send a POST request to my php server and get information as a result. I tried the code without checking isset($_POST['id']) in php and the code worked fine. Buy when I started to check, php will skip the if statement and go to else meaning the code is not sending the params correctly. How can I fix this?

RequestQueue queue = Volley.newRequestQueue(Chat.this);
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
        CHAT_URL_FEED, null,
        new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d("THISSSSSSSS", response.toString());
                if (response != null) {
                    parseChatJsonFeed(response);
                }
            }
        }, new Response.ErrorListener(){

    @Override
    public void onErrorResponse(VolleyError error){
        VolleyLog.d("Here", "Error: " + error.getMessage());
    }
}) {

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

};

queue.add(jsonObjReq);

I also tried the following code:

RequestQueue queue = Volley.newRequestQueue(Chat.this);

        JSONObject params = new JSONObject();
        try {
            params.put("id", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }


        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                CHAT_URL_FEED, params,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d("THISSSSSSSS", response.toString());
                        if (response != null) {
                            parseChatJsonFeed(response);
                        }
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Here", "Error: " + error.getMessage());
            }
        });

        queue.add(jsonObjReq);

but I still get the same result.

Max Pain
  • 1,217
  • 7
  • 19
  • 33
  • possible duplicate of [Google Volley: How to send a POST request with Json data?](http://stackoverflow.com/questions/23220695/google-volley-how-to-send-a-post-request-with-json-data) – SMR Sep 20 '14 at 06:13
  • currently volley does not supports POST method for JSON requests. have a look at [this](http://stackoverflow.com/questions/23220695/google-volley-how-to-send-a-post-request-with-json-data) and [this](http://stackoverflow.com/questions/19837820/volley-jsonobjectrequest-post-request-not-working?rq=1) – SMR Sep 20 '14 at 06:15
  • @Max Pain `I tried the code without checking isset($_POST['id']) in php and the code worked fine.` can you post that, i think `$_POST['id']` is `null` in either cases. – mmlooloo Sep 21 '14 at 06:32
  • @Max Pain would you give me a favour and tell me how do you use **$_POST** in your PHP code to read **JsonObjectRequest**? because i have seen a lot posts about that and still have a problem. – mmlooloo Sep 21 '14 at 16:55
  • here is what I am using to check my code. `if(isset($_POST['id']) && !empty($_POST['id']) && $_POST['id'] != null){//mycode here}` – Max Pain Sep 21 '14 at 18:57
  • @MaxPain you said: and **the code worked fine.** i just want that code.:-) – mmlooloo Sep 22 '14 at 13:38
  • @MaxPain and please start your comment by `@mmlooloo` because i do not get notified. – mmlooloo Sep 22 '14 at 13:57
  • Possible duplicate of [Volley - POST/GET parameters](http://stackoverflow.com/questions/16626032/volley-post-get-parameters) – Andrea Motto Nov 02 '15 at 21:20

6 Answers6

5

After spending some more time looking into this problem, I found out that Volley does not properly work with JSON request with POST requests. User @SMR suggested that in the comment section of my question. I also saw a similar answers on Google groups and the mian repo on git. I ended up using GET requests to pass the information to the server and retrieve a JSON feed.

Max Pain
  • 1,217
  • 7
  • 19
  • 33
  • Hello Max! Thaks for your answer .. what is the alternative to this ??? actually I have a project which has Volley implemented .. but the structure of api's is now being changed by the backend team .. and now I am facing this issue with post request .. please suggest me an alternative to this .. as I don't want to change such a major part of my project .. that would be hell of a burden for me! – Vivek Bhardwaj May 11 '22 at 09:38
4
StringRequest postRequest = new StringRequest(Request.Method.POST, CHAT_URL_FEED,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response) {
                    // response
                  Log.d("THISSSSSSSS", response.toString());
            if (response != null) {
                parseChatJsonFeed(response);
            }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error) {
                    // error
                    VolleyLog.d("Here", "Error: " + error.getMessage());
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
          Map<String, String> params = new HashMap<String, String>();
    params.put("id", id);
    return params;
        }
    };

Volley Doesn't Support Parameters when its requesting for JSONObject. you can get response as JSON String and can convert back to JSON using JSONObject class.

  • Spent one morning on this bug. Volley wants a json to send the request but.... doesn't send that json! Use a POST instead, but IMHO this is a bug. – Caterpillaraoz Mar 21 '20 at 19:09
0

For sent POST request you can write custom request class that based on JsonRequest class P.S. I use this way in my library (based on Volley)

a.black13
  • 2,157
  • 4
  • 19
  • 20
0

You can also send a String request (JSON) as a POST as seen below.

        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        String requestStr = "{\n" +
                "\"id\": \"your JSON\"\n" +
                "}\n";

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,"http://<Your url>",
                requestStr,new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //Your Logic on Success
            }
        },new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //Your Logic on Error
            }
        });

        queue.add(request);
Ruchira Randana
  • 4,021
  • 1
  • 27
  • 24
0

In spite of sending the request as a StringRequest, use JsonObjectRequest. I'm pretty sure the issue will be gone!

Thank me later :)

Vivek Bhardwaj
  • 530
  • 5
  • 16
0

I'm a bit late to answer this, but I think it may help someone facing same problem. I search through all similar questions on SO, relating to PHP and Volley api but I didn't find any satisfying answer.

The problem is that you are sending data from the Volley library as content type

application/json

but your PHP script is expecting POST data as content type

application/x-www-form-urlencoded

In your PHP script, do this:

$_POST = json_decode(file_get_contents('php://input'), true);

if ( !empty($_POST['id']) ) {
    $id = $_POST['id'];
    echo $id;
}

Now if you check for

if( isset($_POST['id']) ){
    echo "something";
}

it should work now

Oposinii
  • 11
  • 2