Volley is sending empty params

2019-08-25 04:31发布

In my android app, I am sending a volley POST request and it's not working. Rather it is sending empty parameters.

If I enter the url (https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail@my.com&content=This_is_a_sampe_comment) in postman and send a POST request it yields the desired result.

And the code generated by Postman looks like this for JAVA OKHttp:

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://blogurl.com/wp-json/wp/v2/comments?post=20081&author_name=Ozuf&author_email=myemail@my.com&content=This_is_a_sampe_comment")
  .post(null)
  .addHeader("cache-control", "no-cache")
  .addHeader("postman-token", "23f2c2587-e9eb-5446-3d73-a1a1a6814683")
  .build();

Response response = client.newCall(request).execute();

This is the code I am using to send the POST request:

public void submitComment() {
        final String comment = commentContent.getText().toString().trim();
        final String name = commentName.getText().toString().trim();
        final String email = commentEmail.getText().toString().trim();
        Log.d(TAG, "submitComment called");


        if (allFieldsAreValid()) {
            Log.d(TAG, "All fields are valid");
            final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?";

            final PostingComment postingComment = PostingComment.newInstance();
            postingComment.show(getFragmentManager(), "fragmentDialog");

            JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());
                            parseResponse(response);
                            postingComment.dismiss();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, "onErrorResponse for getPost called");
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                            postingComment.dismiss();
                            if (sthWrongAlert != null) {
                                sthWrongAlert.show();
                            }
                        }
                    }) {
                @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("post", comtUrl);
                    params.put("author_name", name);
                    params.put("author_email", email);
                    params.put("content", comment);
                    return params;
                }

            };

            int retrytimes = 10;
            RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            postDetails.setRetryPolicy(policy);

            //Creating requestqueue
            RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

            //Adding request queue
            requestQueue.add(postDetails);

            Log.d(TAG, "Data sent is " + comment + name + email);


        } else {
            Log.d(TAG, "All fields are not valid");
        }

    }

And Like I said before, the request goes true but the parameters are not sent along with it.


EDIT

After applying djodjo answer

public void submitComment() {
        String comment = null;
        try {
            comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String name = null;
        try {
            name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String email = null;
        try {
            email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "submitComment called");


        if (allFieldsAreValid()) {
            Log.d(TAG, "All fields are valid");
            final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;

            final PostingComment postingComment = PostingComment.newInstance();
            postingComment.show(getFragmentManager(), "fragmentDialog");

            JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());
                            parseResponse(response);
                            postingComment.dismiss();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, "onErrorResponse for getPost called");
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                            postingComment.dismiss();
                            if (sthWrongAlert != null) {
                                sthWrongAlert.show();
                            }
                        }
                    }) {
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded; charset=UTF-8";
                }

            };

            int retrytimes = 10;
            RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            postDetails.setRetryPolicy(policy);

            //Creating requestqueue
            RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

            //Adding request queue
            requestQueue.add(postDetails);

            Log.d(TAG, "Data sent is " + comment + name + email);


        } else {
            Log.d(TAG, "All fields are not valid");
        }

    }

After applying his solution, that's how my codes looks like. But I am constantly getting error 409.

06-20 19:13:26.405 25586-27084/com.jozuf.blog E/Volley: [6168] BasicNetwork.performRequest: Unexpected response code 409 for https://blog.url/wp-json/wp/v2/comments?post=20081content=Yyggggbbhhgggggg&author_nameRrrauthor_emailgf%40ff.com

3条回答
叛逆
2楼-- · 2019-08-25 05:02

getParams() are not called for JsonRequests.

What you can do is just append to

postComment the extra params. for example:

final String comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
        final String name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
        final String email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");

final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?comment="+comment+"&name="+name+"&email="+email;
查看更多
孤傲高冷的网名
3楼-- · 2019-08-25 05:02

You can send the parameters as JSONObject like this:

JSONObject params = new JSONObject("{\"post\":\"" + comtUrl + "\"," + 
...
+ "}"

and in JsonObjectRequest you pass it as the third parameter.. you will not need getBodyContentType and getParams anymore

查看更多
仙女界的扛把子
4楼-- · 2019-08-25 05:06

After the debugging in chat, the issue found was that it is a POST request but the parameters are still being sent in the request url.

In your case sending a POST response will make the param to go in the body as a multipart form which needs to be fixed. Update you code with below

public void submitComment() {
        String comment = null;
        try {
            comment = URLEncoder.encode(commentContent.getText().toString().trim(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String name = null;
        try {
            name = URLEncoder.encode(commentName.getText().toString().trim(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String email = null;
        try {
            email = URLEncoder.encode(commentEmail.getText().toString().trim(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "submitComment called");


        if (allFieldsAreValid()) {
            Log.d(TAG, "All fields are valid");
            final String postComment = "https://blogurl.com/wp-json/wp/v2/comments?post="+comtUrl+"&content="+comment+"&author_name="+name+"&author_email="+email;

            final PostingComment postingComment = PostingComment.newInstance();
            postingComment.show(getFragmentManager(), "fragmentDialog");

            JsonObjectRequest postDetails = new JsonObjectRequest(Method.POST, postComment, null,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());
                            parseResponse(response);
                            postingComment.dismiss();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d(TAG, "onErrorResponse for getPost called");
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                            postingComment.dismiss();
                            if (sthWrongAlert != null) {
                                sthWrongAlert.show();
                            }
                        }
                    });

            int retrytimes = 10;
            RetryPolicy policy = new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, retrytimes, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
            postDetails.setRetryPolicy(policy);

            //Creating requestqueue
            RequestQueue requestQueue = Volley.newRequestQueue(getActivity());

            //Adding request queue
            requestQueue.add(postDetails);

            Log.d(TAG, "Data sent is " + comment + name + email);


        } else {
            Log.d(TAG, "All fields are not valid");
        }

    }

The duplicate issue is explained in this thread

Just change the request to have this retry policy and it will work

request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
查看更多
登录 后发表回答