4

I am trying hit an api(written in PHP) and posting params with it. Here is my code:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            url, null,
            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    System.out.println("prerna succes volley "+response.toString());
                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            System.out.println("prerna fail volley "+error.toString());
        }
    })


    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> pars = new HashMap<String, String>();
            pars.put("Content-Type", "application/x-www-form-urlencoded");
            return pars;
        }


        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("action", "login");
            params.put("username", "abc@xyz.com");
            params.put("pass", "a");
            return params;
        }

    };

I always get invalid username/password which has been handled in api in case there is invalid username and password.In this case api is not receiving the params. I tried to do it with retrofit and its working fine with it that means there is no problem at API coding. What am I missing here in case of volley?

4 Answers4

6

Thanks for the support. I am able to solve the problem by changing JsonObjectRequest to StringRequest. i found Volley JsonObjectRequest Post parameters no longer work where I got to know that JsonObjectRequest creates some unexpected problems. There is my code:

    StringRequest jsonObjReq = new StringRequest(Request.Method.POST,
            url,
            new com.android.volley.Response.Listener<String>() {

                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response.toString());
                        String no = jsonObject.getString("$PhoneNo");

                    } catch (JSONException e) {

                    }
                }
            }, new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            System.out.println("prerna fail volley " + error.toString());
        }
    })


    {
        @Override
        public String getBodyContentType() {
            Map<String, String> pars = new HashMap<String, String>();
            pars.put("Content-Type", "application/x-www-form-urlencoded");
            //return pars;
            return "application/x-www-form-urlencoded";
        }


        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("action", "login");
            params.put("username", "abc@xyz.com");
            params.put("pass", "a");
            return params;
        }

    };

However I am still trying to figure out why JsonobjectRequest did not work.

Community
  • 1
  • 1
0

As far as I can tell by looking at JsonObjectRequest your 3rd parameter is null, and it indicates the JsonObject request - by the documentation "jsonRequest - A JSONObject to post with the request. Null is allowed and indicates no parameters will be posted along with request."

And after searching again, I saw this thread.

Community
  • 1
  • 1
Erik
  • 73
  • 6
0

Try migrating to getHeaders and remove getParams

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("action", "login");
        params.put("username", "abc@xyz.com");
        params.put("pass", "a");
        return pars;
}

Or - Reuse the getParams method

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = getParams();
        params.put("Content-Type", "application/x-www-form-urlencoded");
        return params;
}

If it is a body request all you need to do is add the extra parameter.

JSONObject body = new JSONObject();
body.put("action", "login");
body.put("username", "abc@xyz.com");
body.put("pass", "a");

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            url, body,

            new com.android.volley.Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    System.out.println("prerna succes volley "+response.toString());
                }
            },
 new com.android.volley.Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

            System.out.println("prerna fail volley "+error.toString());
        }
    });
Enzokie
  • 7,365
  • 6
  • 33
  • 39
0

if you are sending your data in raw format you need to try this,first of all make json of your data to be post.

final JSONObject jsonBody = new JSONObject();
                jsonBody.put("mobile", phoneNumber);
                jsonBody.put("otp", otp.trim());

and you have to override these methods

@Override public byte[] getBody() throws AuthFailureError { return jsonBody.toString().getBytes(); }

            @Override
            public String getBodyContentType() {
                return "application/json";
            }

if you also have header in your post request you also send that with by following type

  @Override
                    public Map<String, String> getHeaders() throws AuthFailureError {
                        Map<String, String> params = new HashMap<String, String>();
                        String auth_token = "bearer" + prefs.getPreferencesString(context, "AuthToken").toString();
                        params.put("Authorization", auth_token);
                        return params;
                    }

Here is the whole code.

 final JSONObject jsonBody = new JSONObject();
                jsonBody.put("mobile", phoneNumber);
                jsonBody.put("otp", otp.trim());

                StringRequest sr = new StringRequest(Request.Method.POST, Constraints.Base_URL + "/api/v1/verifyotp", new com.android.volley.Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            progressDialog.dismiss();
                            JSONObject jsonObject = new JSONObject(response);
                            int status = jsonObject.getInt("status");
                            String token = jsonObject.getString("token");
                            prefs.setPreferencesString(OtpActivity.this, "AuthToken", token);

                            if (status == 1) {

                                startActivity(new Intent(getApplicationContext(), WelcomeScreenActivity.class));
                                overridePendingTransition(R.anim.right_in, R.anim.left_out);
                            } else if (status == 0) {
                                Toast.makeText(OtpActivity.this, "Please Enter Otp!", Toast.LENGTH_SHORT).show();
                            }
                        } catch (Exception e) {

                        }
                    }
                }, new com.android.volley.Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                        Toast.makeText(OtpActivity.this, "Invalid otp please try again!!", Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                }) {

                    @Override
                    public byte[] getBody() throws AuthFailureError {
                        return jsonBody.toString().getBytes();
                    }

                    @Override
                    public String getBodyContentType() {
                        return "application/json";
                    }
                };

                MyApplication.getInstance().addToReqQueue(sr, "jreq");
            }
        } catch (Exception e) {

        }
Jyoti
  • 255
  • 2
  • 7