Google Volley ignores POST-Parameter
Asked Answered
C

5

4

I'm currently trying to send a simple POST-request via Google Volley to my server. Therefore I've written the following lines of code:

Map<String, String> params = new HashMap<String, String>();
params.put("regId", "skdjasjdaljdlksajskl");
JSONObject object = new JSONObject(params);
JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                "address_of_my_server/method", object,
                successListener, errorListener);
queue.add(request);

But I get an Error 500 returned, which says, that there is a missing parameter (regId). I've tried the same with a GET-Request, but I got the same result.

Only when I'm using a StringRequest with a formatted URL like "address_of_my_server/method?regId=sadlasjdlasdklsj" the server replies with 200.

I get the exact same result when I use a StringRequest like:

StringRequest request = new StringRequest(Method.POST,
                "myurl", successListener,
                errorListener){
            @Override
            protected Map<String, String> getParams()
                    throws AuthFailureError {
               Map<String, String> params = new HashMap<String, String>();
               params.put("regId", "skdjasjdaljdlksajskl");
               return params;
            }
        };

Why is Volley ignoring my parameters?

Ceaseless answered 4/11, 2013 at 1:6 Comment(4)
by design, aren't parameters always delivered in the URL? I think the JSON object is the data portion of the requestBureaucrat
hm.. you're might be right. But shouldn't my StringRequest add these parameters automatically to the URL?Ceaseless
it looks like the params are only sent in a POST request, not in a GET like you mentioned, did you try it that way?Bureaucrat
Does you regId on the server accepts string? Looks like it expects an Integer.Gabrila
O
1

EDIT:

I deleted my previous answer since it wasn't accurate.

I'll go over what I know today: Apparently, getParams should work. But it doesn't always. I have debugged it myself, and it seems that it is being called when performing a PUT or POST request, and the params provided in that method are in a regular GET parameters string (?param1=value1&param2=value2...) and encoded and put in the body.

I don't know why but for some reason this doesn't work for some servers.

The best alternate way I know to send parameters, is to put your parameters in a JSONObject and encode its contents in the request's body, using the request constructor.

Orazio answered 4/11, 2013 at 8:20 Comment(7)
you mean only for POST or PUT messages don't you? "Returns a Map of parameters to be used for a POST or PUT request."Ceaseless
Yeah, lost concentration there for a moment... thanksOrazio
@ItaiHanski but the request Frame91 was talking about was a POST, wasn't it? So why getParams() is not called? I have the same problem in my application: making a POST request the getParams() method is not called.Lor
It is weird. I posted an answer on you question but it should work. Post request take the parameters and encode them in the body. Not sure what's happening. Better debug.Orazio
Don't know why this answer is accepted. The reason is that server side takes form post format instead of json data.Typhus
@Typhus you are correct. I updated this old answer to be more accurate.Orazio
The getParams method only returns Map<String, String> I need to be able to POST Submit a form with Map<String,Object> (which contains a complex JSON tree structure). What do i do in this situation? I tried passing in a JSONObject into the constructor, but it appears to be getting ignored for other server POST requests, which just pass String: String. Only getParams works, when returning the Map<String,String>. So i have no solution for passing in Map<String,Object> right now.Aretino
T
3

I had same issue last week, but it is fixed now. Your server accepts the Content-Type as form-data, when sending volley's JsonObjectRequest the request's content-type will be application/json so whole params will be sent as one json body, not as key value pairs as in Stringrequest. Change the server code to get request params from http request body instead of getting it from keys(like $_REQUEST['name'] in php).

Translatable answered 7/11, 2013 at 3:16 Comment(0)
G
3

Use this helper class:

import java.io.UnsupportedEncodingException;
import java.util.Map;    
import org.json.JSONException;
import org.json.JSONObject;    
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {

private Listener<JSONObject> listener;
private Map<String, String> params;

public CustomRequest(String url, Map<String, String> params,
        Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

public CustomRequest(int method, String url, Map<String, String> params,
        Listener<JSONObject> reponseListener, ErrorListener errorListener) {
    super(method, url, errorListener);
    this.listener = reponseListener;
    this.params = params;
}

protected Map<String, String> getParams()
        throws com.android.volley.AuthFailureError {
    return params;
};

@Override
protected Response<JSONObject> 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) {
    // TODO Auto-generated method stub
    listener.onResponse(response);
    }
}
Gilliland answered 13/11, 2013 at 4:52 Comment(1)
This solves my problem. On the PHP side, I use Codeigniter framework so I can use $this->input->post() to handle the input safely, instead of writing my own escape code to avoid sql injection.Typhus
T
2

Woking example with the issue that Rajesh Batth mentioned

Java code:

    JSONObject obj = new JSONObject();
    try {
        obj.put("id", "1");
        obj.put("name", "myname");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    JsonObjectRequest jsObjRequest = new JsonObjectRequest(
            Request.Method.POST, url, obj, listener, errorlistener);

    RequestQueue queue = Volley.newRequestQueue(context);
    queue.add(jsObjRequest);

PHP-Code:

    $body = file_get_contents('php://input');
    $postvars = json_decode($body, true);
    $id = $postvars["id"];
    $name = $postvars["name"];

Note:

The PHP-Vars $_POST and $_REQUEST and $_GET are empty if you are not sending additional GET-VARS.

Trochanter answered 13/2, 2014 at 10:15 Comment(0)
O
1

EDIT:

I deleted my previous answer since it wasn't accurate.

I'll go over what I know today: Apparently, getParams should work. But it doesn't always. I have debugged it myself, and it seems that it is being called when performing a PUT or POST request, and the params provided in that method are in a regular GET parameters string (?param1=value1&param2=value2...) and encoded and put in the body.

I don't know why but for some reason this doesn't work for some servers.

The best alternate way I know to send parameters, is to put your parameters in a JSONObject and encode its contents in the request's body, using the request constructor.

Orazio answered 4/11, 2013 at 8:20 Comment(7)
you mean only for POST or PUT messages don't you? "Returns a Map of parameters to be used for a POST or PUT request."Ceaseless
Yeah, lost concentration there for a moment... thanksOrazio
@ItaiHanski but the request Frame91 was talking about was a POST, wasn't it? So why getParams() is not called? I have the same problem in my application: making a POST request the getParams() method is not called.Lor
It is weird. I posted an answer on you question but it should work. Post request take the parameters and encode them in the body. Not sure what's happening. Better debug.Orazio
Don't know why this answer is accepted. The reason is that server side takes form post format instead of json data.Typhus
@Typhus you are correct. I updated this old answer to be more accurate.Orazio
The getParams method only returns Map<String, String> I need to be able to POST Submit a form with Map<String,Object> (which contains a complex JSON tree structure). What do i do in this situation? I tried passing in a JSONObject into the constructor, but it appears to be getting ignored for other server POST requests, which just pass String: String. Only getParams works, when returning the Map<String,String>. So i have no solution for passing in Map<String,Object> right now.Aretino
B
0

Thi's my solution

Solution 1

 public void getData() {
    final RequestQueue queue = Volley.newRequestQueue(this);
    StringRequest postRequest = new StringRequest(Request.Method.POST, "192.168.0.0/XYZ",new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONArray myArray = new JSONArray(response);

                        for(int i = 0; i < myArray.length(); i++)
                        {
                            JSONObject jObj = myArray.getJSONObject(i);
                            String category = jObj.getString("nameUser");
                            Log.e("value", category);

                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("error: ", e.getMessage());
                    }

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //Toast.makeText(context,"Error : ").show();
        }
    }){
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("id_user", "1");
            return params;
        }
    };
    queue.add(postRequest);
}

Solution 2

remember that if you use php,the $_POST[''];
not working, her more information.

Good Luck

Balkanize answered 18/9, 2015 at 5:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.