Volley not sending a post request with parameters.
Asked Answered
A

6

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.

Aerostation answered 20/9, 2014 at 5:43 Comment(8)
possible duplicate of Google Volley: How to send a POST request with Json data?Nephoscope
currently volley does not supports POST method for JSON requests. have a look at this and thisNephoscope
@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.Pert
@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.Pert
here is what I am using to check my code. if(isset($_POST['id']) && !empty($_POST['id']) && $_POST['id'] != null){//mycode here}Aerostation
@MaxPain you said: and the code worked fine. i just want that code.:-)Pert
@MaxPain and please start your comment by @mmlooloo because i do not get notified.Pert
Possible duplicate of Volley - POST/GET parametersIllyes
A
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.

Aerostation answered 28/9, 2014 at 9:13 Comment(1)
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!Extranuclear
M
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.

Miramontes answered 17/11, 2016 at 12:11 Comment(1)
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.Present
P
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)

Pilsudski answered 8/1, 2015 at 9:38 Comment(0)
C
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);
Churchwarden answered 12/3, 2016 at 6:42 Comment(0)
E
0

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

Thank me later :)

Extranuclear answered 11/5, 2022 at 10:49 Comment(0)
C
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

Custer answered 21/5, 2022 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.