凌空正在发送空的参数

时间:2016-06-20 01:43:07

标签: android wordpress android-volley postman

在我的Android应用程序中,我发送一个凌空POST请求,但它无法正常工作。而是发送空参数。

如果我在邮递员中输入网址(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请求,则会产生所需的结果。

Postman生成的代码对于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();

这是我用来发送POST请求的代码:

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

    }

就像我之前说过的那样,请求成立,但参数不会随之发送。

修改

应用djodjo回答后

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

    }

应用他的解决方案后,这就是我的代码的样子。但我经常收到错误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 个答案:

答案 0 :(得分:3)

在聊天调试后,发现的问题是它是POST请求,但参数仍在请求网址中发送。

在您的情况下,发送POST响应将使该参数作为需要修复的多部分表单进入正文。使用下面的代码更新代码

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

    }

thread

中解释了重复的问题

只需将请求更改为具有此重试策略即可生效

request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

答案 1 :(得分:0)

不为JsonRequests调用

getParams()。

你可以做的只是追加到

  

post评论额外的参数。例如:

Id    Name    Avatar        Dept        School
1     Mark    01019.jpg     Market      None
2     John    21122.jpg     Business    None
3     Sam     33311.jpg     IT          None
....
....
50    James   9823.jpg      IT          USA

答案 2 :(得分:-1)

您可以像JSONObject一样发送参数:

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

并在JsonObjectRequest中将其作为第三个参数传递..您不再需要getBodyContentTypegetParams