Post Method using Volley not working

2020-02-01 12:51发布

问题:

Hi i am using Volley for my login page. I need to pass data like this manner

{
userID : '-988682425884628921',
email :'aditya@vyas.com',
passwd : '123ss'
}

I am using POST Method to send data,I already check in DHC, The Api is working fine in DHC and I am getting JSON Response, But when i try with Volley i am not able to get response. and not even any error in my logcat.

JAVA code

 RequestQueue mVolleyQueue = Volley.newRequestQueue(this);

    CustomRequest req = new CustomRequest(Request.Method.POST,url,null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.v("tag","login response " + response);
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.v("tag","login error response " + error.getMessage());
        }
    }){
        @Override
        public Map<String, String> getParams() throws AuthFailureError {
            Map<String, String>  params = new HashMap<String, String>();

            params.put("userID", "-988682425884628921");
            params.put("email", "aditya@vyas.com");
            params.put("passwd", "123ss");
            return params;
        }


            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> headers = new HashMap<String, String>();
                headers.put("Content-Type", "application/json; charset=utf-8");
                return headers;
        }
    };
    mVolleyQueue.add(req);

Error

05-28 09:20:14.696 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError is ! null
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError status code : 400
05-28 09:20:14.697 2450-2468/com.android.msahakyan.expandablenavigationdrawer E/tag﹕ parseNetworkError message : <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Header</h2>
<hr><p>HTTP Error 400. The request has an invalid header name.</p>
</BODY></HTML>


    }

回答1:

Solved your problem. Just used JsonArrayRequest and passed parameters in JsonObject form:

    Map<String, String> params = new HashMap<String, String>();
    params.put("userID", "userid");
    params.put("email","email");
    params.put("passwd", "password");
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.POST, "url", new JSONObject(params),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    System.out.println("response -->> " + response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    System.out.println("change Pass response -->> " + error.toString());
                }
            });

    request.setRetryPolicy(new

            DefaultRetryPolicy(60000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));


    Volley.newRequestQueue(activity).add(request);

No need of overriding getParams() or getHeaders().

Problem : 1 You were getting response code 500 because the server was accepting the params as JsonObject and we are trying to feed String.

Problem : 2 You were using JsonObjectRequet but the response from the server was in JsonArray so you need to use JsonArrayRequest to accept the response in JsonArray

Try and let me know this helps or not :)



回答2:

I had a similar problem. I had overwritten the Content-Type in the getHeaders Method:

headers.put("Content-Type", "application/json; charset=UTF-8");

but Volley itself added a Content-Type parameter, so there were two of those parameters. Delete the line had solved my Problem.



回答3:

You need to override protected Map<String, String> getParams() to pass parameters in POST.

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

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


                   hidepDialog();
                }
            }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            System.out.println(error.getStackTrace());
            VolleyLog.d("ErrorVolley", "Error: " + error.getStackTrace());
            hidepDialog();
        }
    }) {

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("userID", "2"));
                params.put("email","aa@a.kl");
                params.put("passwd", "ddddd");

                return params;
            }
        };



回答4:

Beware of content-type header. Volley handles it differently from other headers and it's not shown in Map<> Headers. Instead of overriding getHeaders() method to set content-type, you should override getBodyContentType() like this:

@Override
public String getBodyContentType()
{
    return "application/json; charset=utf-8";
}


回答5:

i have same problem use this :

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast.makeText(LoginActivity.this, response, Toast.LENGTH_LONG).show();

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(LoginActivity.this, error.toString(), Toast.LENGTH_LONG).show();

                }
            }) {

        @Override
        public Map<String, String> getParams()  {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            headers.put("UN", UserName);
            headers.put("PW", PassWord);
            return headers;


        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue(this);
     requestQueue.add(stringRequest);

Just need to add headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); to parms

good luck.