Post Method using Volley not working
Asked Answered
E

5

5

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

{
userID : '-988682425884628921',
email :'[email protected]',
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", "[email protected]");
            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>


    }
Earful answered 27/5, 2016 at 10:34 Comment(6)
Try using StringRequest instead of JsonObjectRequest. I see that the JSON is in JSONArray format, so that might be the problem.Lynnett
@SomnathPal stringrequest also not workingEarful
You are passing parameters in body, need to override getParams() method and pass parameters thereCivil
@Civil i tried with Arth Tilva's answer tooEarful
What is JsonStringRequestEarful
Have tried for JsonArrayRequest ? coz i m seeing your response in JSONArray..!!Unpredictable
U
6

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 :)

Unpredictable answered 28/5, 2016 at 4:56 Comment(0)
T
4

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.

Totter answered 12/12, 2016 at 17:30 Comment(2)
You made my day, have been struggling since hours, and this was the reason :)Genista
you rock dude, I am from 2020 here ahahahahahScrogan
G
1

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","[email protected]");
                params.put("passwd", "ddddd");

                return params;
            }
        };
Gearard answered 27/5, 2016 at 10:46 Comment(10)
still same no change ::(Earful
if change it with stringrequest it shows BasicNetwork.performRequest: Unexpected response code 500 forEarful
I checked about Error 500 and found that this error may be caused from the server side. Its not any fault of your code @AdityaVyasLynnett
Don't have experience with DHC, but if its working in Postman (using POST) then you should get atleast response from your web service.Lynnett
500 is the server side exception, contact web dev. and ask why it is throwing exception.Gearard
might be you are not sending all parameters you need to, then also it may thtrow exceptionGearard
@ArthTilva i am sending same parameter which i have in DHC and there i am able to get response :(Earful
If you can provide the API link and params, I can check.Lynnett
It may happen your server is only accepting JSON and you might be sending string.Unpredictable
@jankigadhiya then what is the solution for thatEarful
A
0

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";
}
Alcina answered 10/8, 2017 at 14:44 Comment(0)
C
0

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.

Corsair answered 9/3, 2018 at 0:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.