Google Volley ignores POST-Parameter

回眸只為那壹抹淺笑 提交于 2019-11-29 07:59:31

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.

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).

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!