姬長信(Redy)

带有标题和正文的Android Volley POST请求


我的代码正在尝试将数据发布到服务器,并且需要添加标头,我正在使用Volley库.

如果我不包含“ getparams”方法,则该请求有效,我可以发布但没有数据.

如果我包含“ getparams”方法,则请求失败,并显示400(错误请求).

我一直无法找出错误所在.

         public void tryPost() {
    RequestQueue queue = Volley.newRequestQueue(this);

    String serverUrl = "http://10.0.2.2:3000/tasks";



    StringRequest stringRequest = new StringRequest(Request.Method.POST, serverUrl,
            new Response.Listener() {
                @Override
                public void onResponse(String response) {
                    Log.d("TAG", "response = "+ response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("TAG", "Error = "+ error);
        }
    })
    {
        //
        @Override
        public Map getHeaders()  {
            HashMap headers = new HashMap();
            headers.put("Accept", "application/json");
            headers.put("Content-Type", "application/json");
            return headers;
        }
        ////
        @Override
        public Map getParams() {
            Map params = new HashMap();
            params.put("userId","sargent"); 
            params.put("password","1234567"); 
            return params; //return the parameters
        }
    };
    // Add the request to the RequestQueue.
    queue.add(stringRequest);
    }