3

Following is my Volley POST method Call. The POST parameters does not pass the data to web server/API tried almost everything like 1. Override byte[] getBody() 2. Parameter Type 3. Using JsonRequest

Parsing four POST parameters to the server and based on this going have response. What is missing in this code??

private void generateTicket(final String field1, final String field2 , final String field3, final String field4) {

    StringRequest strReq = new StringRequest(Method.POST,
                    AppConfig.URL_GENERATION, new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jObj = new JSONObject(response);
                                boolean error = jObj.getBoolean("error");

                                // Check for error node in json
                                if (!error) {
                                // SUCCESS CODE GOES HEAR

                                } else {
                                    // Error in login. Get the error message
                                    String errorMsg = jObj.getString("msg");
                                    Toast.makeText(getApplicationContext(),
                                            errorMsg, Toast.LENGTH_LONG).show();
                                }
                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e(TAG, "API Error: " + error.getMessage());
                            Toast.makeText(getApplicationContext(),
                                    error.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }) {

                @Override
                protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {  
                    // Posting parameters to the url
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("tag", "generate");
                    params.put("field1", field1);
                    params.put("field2", field2);
                    params.put("field3", field3);
                    params.put("field4", field4);           
                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String,String> params = new HashMap<String, String>();
                    params.put("Content-Type","application/x-www-form-urlencoded");
    //              params.put("Content-Type", "application/json");
                    return params;
                }

            };
            // Adding request to request queue
            AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
    }
Mochamad Taufik Hidayat
  • 1,264
  • 3
  • 21
  • 32
Amit Modak
  • 169
  • 3
  • 8

5 Answers5

2

Please try request.setShouldCache(false); before add the request to the queue. I guess maybe it'll help.

By default, volley will cache the response. When it meets the url again, it will get from its cache not from the web. Even after reinstall app (like you do in debug), the cache is still here. But uninstall and install will clear the cache.

If you use the POST method, don't use the JsonRequest. It simply doesn't call getParams().

Kay Wu
  • 759
  • 6
  • 9
2

Something very weird turned out to be the solution in my case:

my connection URL was

http://something.com/folder1/folder2

with folder2 containing an index.php file inside it, which processed the request.

changing it to

http://something.com/folder1/folder2/ (adding the / at the end) solved the problem, and the server received the POST data

No idea why , but I've seen this before. Almost impossible to find out, no one talks about this. Hopefully this answer may help someone.

Matheus Valin
  • 191
  • 2
  • 8
0

Are you getting any error? If so please update your post. Code looks fine above. However you can use the following code if you still have problem

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
            url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, response.toString());
                    pDialog.hide();
                }
            }, new Response.ErrorListener() {

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

        /**
         * Passing some request headers
         * */
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            headers.put("apiKey", "xxxxxxxxxxxxxxx");
            return headers;
        }

    };

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
Vinay Jayaram
  • 1,030
  • 9
  • 29
0

this one worked for me (seen on Volley JsonObjectRequest Post parameters no longer work)

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.GET, 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);
Community
  • 1
  • 1
yasin
  • 270
  • 4
  • 6
0

It also took me a while now to get my request working, so here I am posting my solution as it might help some of you:

    val url = " https://example.com"

    val jsonObjectRequest: JsonObjectRequest = object : JsonObjectRequest(
        Method.POST, url, null,
        { response ->
            Log.d("jsonResponse", response.toString())
        },
        { error ->
               Log.d("jsonResponse", error.toString())
        }) {

        override fun getBody(): ByteArray {
            return "api_token=<token>&id=<id>".toByteArray()
        }

        override fun getHeaders(): MutableMap<String, String> {
            val params: MutableMap<String, String> = HashMap()
            params["Content-Type"] = "application/x-www-form-urlencoded"
            return params            }
    }
    Volley.newRequestQueue(requireContext()).add(jsonObjectRequest)

So the problem in my case was that I couldn't pass the parameters as a Hashmap, but just the string was needed to be passed through the getBody() override function. Additionally the headers needed to be set explicitely in override getHeaders(). The JSONObject that could be passed as a parameter is set to null as it was always ignored.

Patrick Lang
  • 501
  • 6
  • 9