Volley JsonObjectRequest Post parameters no longer

2019-01-05 03:35发布

I am trying to send POST parameters in a Volley JsonObjectRequest. Initially, it was working for me by following what the official code says to do of passing a JSONObject containing the parameters in the constructor of the JsonObjectRequest. Then all of a sudden it stopped working and I haven't made any changes to the code that was previously working. The server no longer recognizes that any POST parameters are being sent. Here is my code:

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";

// POST parameters
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "test");

JSONObject jsonObj = new JSONObject(params);

// Request a json response from the provided URL
JsonObjectRequest jsonObjRequest = new JsonObjectRequest
        (Request.Method.POST, url, jsonObj, new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response)
            {
                Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT).show();
            }
        },
        new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {
                Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
            }
        });

// Add the request to the RequestQueue.
queue.add(jsonObjRequest);

Here is the simple tester PHP code on the server:

$response = array("tag" => $_POST["tag"]);
echo json_encode($response);

The response I get is {"tag":null}
Yesterday, it worked fine and was responding with {"tag":"test"}
I haven't changed a single thing, but today it is no longer working.

In the Volley source code constructor javadoc it says that you can pass a JSONObject in the constructor to send post parameters at "@param jsonRequest": https://android.googlesource.com/platform/frameworks/volley/+/master/src/main/java/com/android/volley/toolbox/JsonObjectRequest.java

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *       indicates no parameters will be posted along with request.

I have read other posts with similar questions, but the solutions haven't worked for me:

Volley JsonObjectRequest Post request not working

Volley Post JsonObjectRequest ignoring parameters while using getHeader and getParams

Volley not sending a post request with parameters.

I've tried setting the JSONObject in the JsonObjectRequest constructor to null, then overriding and setting the parameters in the "getParams()", "getBody()", and "getPostParams()" methods, but none of those overrides has worked for me. Another suggestion was to use an additional helper class that basically creates a custom request, but that fix is a bit too complex for my needs. If it comes down to it I will do anything to make it work, but I am hoping that there is a simple reason as to why my code was working, and then just stopped, and also a simple solution.

11条回答
戒情不戒烟
2楼-- · 2019-01-05 03:39

You can do it this way:

CustomRequest request = new CustomRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
           // Toast.makeText(SignActivity.this, response.toString(), Toast.LENGTH_SHORT).show();

            Log.d("response",""+response.toString());

            String status =  response.optString("StatusMessage");
            String actionstatus = response.optString("ActionStatus");
            Toast.makeText(SignActivity.this, ""+status, Toast.LENGTH_SHORT).show();
            if(actionstatus.equals("Success"))
            {
                Intent i = new Intent(SignActivity.this, LoginActivity.class);
                startActivity(i);
                finish();
            }
            dismissProgress();

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(SignActivity.this, "Error."+error.toString(), Toast.LENGTH_SHORT).show();
            Log.d("response",""+error.toString());
            dismissProgress();
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }

        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Email", emailval);
            params.put("PassWord", passwordval);
            params.put("FirstName", firstnameval);
            params.put("LastName", lastnameval);
            params.put("Phone", phoneval);
            return params;
        }

    };
    AppSingleton.getInstance(SignActivity.this.getApplicationContext()).addToRequestQueue(request, REQUEST_TAG);

as per CustomRequest below link Volley JsonObjectRequest Post request not working

查看更多
姐就是有狂的资本
3楼-- · 2019-01-05 03:40

You can use StringRequest to do the same things you can wtih JsonObjectRequest, while still beeing able to easily send POST parameters. The only thing you have to do is to create a JsonObject out of the request String you get, and from there you can continue as if it were JsonObjectRequest.

StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            //Creating JsonObject from response String
                            JSONObject jsonObject= new JSONObject(response.toString());
                            //extracting json array from response string
                            JSONArray jsonArray = jsonObject.getJSONArray("arrname");
                            JSONObject jsonRow = jsonArray.getJSONObject(0);
                            //get value from jsonRow
                            String resultStr = jsonRow.getString("result");
                        } catch (JSONException e) {

                        }

                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                }){
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String,String> parameters = new HashMap<String,String>();
                        parameters.put("parameter",param);

                        return parameters;
                    }

                };
                requestQueue.add(stringRequest);
查看更多
孤傲高冷的网名
4楼-- · 2019-01-05 03:43

It does work.
I parsed json object response using this:- works like a charm.

String  tag_string_req = "string_req";
        Map<String, String> params = new HashMap<String, String>();
        params.put("user_id","CMD0005");

        JSONObject jsonObj = new JSONObject(params);
String url="" //your link
        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
                url, jsonObj, new Response.Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                Log.d("responce", response.toString());

                try {
                    // Parsing json object response
                    // response will be a json object
                    String userbalance = response.getString("userbalance");
Log.d("userbalance",userbalance);
                    String walletbalance = response.getString("walletbalance");
                    Log.d("walletbalance",walletbalance);

                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(),
                            "Error: " + e.getMessage(),
                            Toast.LENGTH_LONG).show();
                }

            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();

            }
        });

        AppControllerVolley.getInstance().addToRequestQueue(jsonObjReq, tag_string_req);

good luck! good night!

查看更多
Deceive 欺骗
5楼-- · 2019-01-05 03:47

You just have to make a JSONObject from your HashMap of parameters:

String url = "https://www.youraddress.com/";

Map<String, String> params = new HashMap();
params.put("first_param", 1);
params.put("second_param", 2);

JSONObject parameters = new JSONObject(params);

JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url, parameters, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        //TODO: handle success
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        error.printStackTrace();
        //TODO: handle failure
    }
});

Volley.newRequestQueue(this).add(jsonRequest);
查看更多
放我归山
6楼-- · 2019-01-05 03:48

I ended up using Volley's StringRequest instead, because I was using too much valuable time trying to make JsonObjectRequest work.

RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://myserveraddress";

StringRequest strRequest = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        Toast.makeText(getApplicationContext(), error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<String, String>();
                params.put("tag", "test");
                return params;
            }
        };

queue.add(strRequest);

This worked for me. Its just as simple as JsonObjectRequest, but uses a String instead.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-05 03:49

Might help someone and save you some time thinking. I had a similar issue, the server code was looking for the Content-Type header. It was doing it this way:

if($request->headers->content_type == 'application/json' ){ //Parse JSON... }

But Volley was sending the header like this:

'application/json; charset?utf-8'

Changing the server code to this did the trick:

if( strpos($request->headers->content_type, 'application/json') ){ //Parse JSON... 
查看更多
登录 后发表回答