2
  • I am getting false response while hitting the post response api using volley.Below I have posted the json format.

  • And also I have posted what I had tried so far in mainactivity.java.

  • I don't know What I did wrong.But i am getting a false response simply.I referred these Sample to do a post with inner json object response to server.

Json Format : (Edited)

    {
"facebookData":{
      "about" : "",
    "access_token":"",
    "age":28,
    "birthday":"563221800",
    "email":"mailtosteve3@gmail.com",
    "facebook_user_id":"561394210664929",
    "first_name":"Bradley",
    "gender":"male",
    "id":"561394210664929",
    "is_show_only":"Men and Women",
    "latitude":"13.05505200",
    "longitude":"80.23623600",
    "name":"Bradley Cummings",
    "profilePicture":"",
    "provider":"Facebook"
}
}

MainActivity.java: (Edited)

  private void validateUser() {


        final ProgressDialog dialog = ProgressDialog.show(FacebookActivity.this, null, null);
        ProgressBar spinner = new android.widget.ProgressBar(FacebookActivity.this, null, android.R.attr.progressBarStyle);
        spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#009689"), android.graphics.PorterDuff.Mode.SRC_IN);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        dialog.setContentView(spinner);
        dialog.setCancelable(false);
        dialog.show();

        try {

            RequestQueue queue = Volley.newRequestQueue(FacebookActivity.this);

            String userValidationURL = BurblrUtils.BR_FB;

            Log.e("userValidationURL", userValidationURL);


            jsonWholeObject = new JSONObject();
            JSONObject jsonFaceBook = new JSONObject();


            jsonFaceBook.put("about", "Note");
            jsonFaceBook.put("access_token", facebookAccessToken);
            jsonFaceBook.put("age", "28");
            jsonFaceBook.put("birthday", "563221800");
            jsonFaceBook.put("email", emailString);
            jsonFaceBook.put("facebook_user_id", faceBookId);
            jsonFaceBook.put("first_name", firstString);
            jsonFaceBook.put("gender", genderString);
            jsonFaceBook.put("id", id);
            jsonFaceBook.put("is_show_only", "Men and Women");
            jsonFaceBook.put("latitude", "13.05505200");
            jsonFaceBook.put("longitude", "80.23623600");
            jsonFaceBook.put("name", firstString + lastString);
            jsonFaceBook.put("profilePicture", profile_pic);
            jsonFaceBook.put("provider", "Facebook");

            jsonWholeObject.put("facebookData", jsonFaceBook);

            mRequestBody = jsonWholeObject.toString();

            StringRequest request = new StringRequest(Request.Method.POST, userValidationURL, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {

                    Log.e("FaceBookRes", response);

                    if (response != null && !response.startsWith("<HTML>")) {

                        Log.e("onResponse", "" + response);
                        dialog.dismiss();

                        try {


                            JSONObject login_obj = new JSONObject(response);

                            String message = login_obj.getString("message");
                            String error = login_obj.getString("error");

                            if (message.equals("Facebook Connection problem")) {

                                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();

                            } else {

                                Log.e("Else...", "Else...");

                                Intent intent = new Intent(FacebookActivity.this, HomeActivity.class);
                                startActivity(intent);
                                finish();


                            }
                        } catch (JSONException e) {

                            e.printStackTrace();

                        }

                    } else {
                        dialog.dismiss();

                        Toast.makeText(getApplicationContext(), "Internet Toast Message", Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error != null) {
                        Log.e("error", error.toString());
                        dialog.dismiss();
                    }
                }
            }) {
                @Override
                public String getBodyContentType() {
                    return "application/json; charset=utf-8";
                }

                @Override
                public byte[] getBody() throws AuthFailureError {
                    try {

                        mRequestBody = jsonWholeObject.toString();

                        return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
                    } catch (UnsupportedEncodingException uee) {
                        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                                mRequestBody, "utf-8");
                        return null;
                    }
                }

                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                    String responseString = "";
                    if (response != null) {
                        responseString = String.valueOf(response.statusCode);
                        // can get more details such as response.headers
                    }
                    return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
                }

            };


            queue.add(request);

        } catch (JSONException je) {

            je.printStackTrace();

        }
      }

Logcat:

04-01 06:45:15.606 12667-12667/? E/FaceBookRes: 200
04-01 06:45:15.606 12667-12667/? E/onResponse: 200
BNK
  • 23,994
  • 8
  • 77
  • 87
Stephen
  • 9,899
  • 16
  • 90
  • 137
  • 1
    Override `getBodyContentType` to `public String getBodyContentType() { return "application/json; charset=" + getParamsEncoding(); }` and also override `getBody()` and use this method instead of `getParams` –  Mar 31 '16 at 15:07
  • 1
    If you use `StringRequest`, please read http://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body/33578202#33578202 to see if it can help. Moreover, test your web service with some requests from Postman and post screenshot of sucessful result – BNK Apr 01 '16 at 09:17
  • @BNK in postman I am getting the right response – Stephen Apr 01 '16 at 09:27
  • 1
    If so, please post the screenshot of Postman so that we can check the request details – BNK Apr 01 '16 at 09:30
  • @BNK I haved edited and posted full raw data.moreover I have added the response result in this [pastie](http://pastie.org/private/demzjpdxzrwqtgeiip8quw) – Stephen Apr 01 '16 at 09:54
  • remove `queue.getCache().remove(userValidationURL);` –  Apr 01 '16 at 12:38
  • @MML13 after removing that one,it is showing that same error.Any suggestion. – Stephen Apr 01 '16 at 12:42
  • I know but you must not remove from cache right after you put it into the queue. –  Apr 01 '16 at 12:43
  • Why do you use `responseString = String.valueOf(response.statusCode);` why do you override `parseNetworkResponse` we need the response not `statusCode`. statusCode is 2xx because the response is going to `onResponse` and not to `onErrorResponse` that is not helpful at all –  Apr 01 '16 at 12:49
  • @MML13 with the help of this [Sample](http://stackoverflow.com/questions/33573803/how-to-send-a-post-request-using-volley-with-string-body/33578202#33578202).I did like that .especially BNK post helped me.So that I understood I have to use getBody() in volley.I will remove that responseString and I will tell you. – Stephen Apr 01 '16 at 12:52
  • @Naturo only use parseNetworkResponse if you have the same requirement as the OP in that link. For your current issue, you don't need to use that method :), getBody is enough, I think. – BNK Apr 01 '16 at 13:19
  • @Naturo the requirement of the OP in that link is "and retrieve the raw response of the web service (like 200 ok, 500 server error)." :). Moreover, if the response from your web service is a JSONObject, you can also use JsonObjectRequest instead of StringRequest, then you don't have to override getBody(). – BNK Apr 01 '16 at 13:25
  • @MML13 Thank you for your suggestion – Stephen Apr 01 '16 at 13:42
  • 1
    you are welcome, actually all you need is my first comment :-) –  Apr 01 '16 at 13:46

3 Answers3

1

As my comments, you can refer to the sample code at my answer at the following question (pay attention to getBody(). If the response from your web service is a JSONObject, you can use JsonObjectRequest instead of StringRequest)

How to send a POST request using volley with string body?

Community
  • 1
  • 1
BNK
  • 23,994
  • 8
  • 77
  • 87
0

this way you should make your JSON

        JSONObject jsonWholeObject  = new JSONObject();

        JSONObject jsonFaceBook  = new JSONObject();
        try {

            jsonFaceBook.put("age", "28");
            jsonFaceBook.put("birthday", "563221800");

            jsonFaceBook.put("first_name", "Bradley");
            jsonFaceBook.put("gender", "male");
            jsonFaceBook.put("provider", "Facebook");


        } catch (JSONException e) {
            e.printStackTrace();
        }

        jsonWholeObject.put("email", "steve123@gmail.com" );
        jsonWholeObject.put("loginData", jsonFaceBook);

Then you can use it in a volley request

user3290180
  • 4,260
  • 9
  • 42
  • 77
  • Now also I am getting false response. I have added params like this. `params.put("email", jsonWholeObject.toString() ); params.put("facebookData", jsonWholeObject.toString()) ;` – Stephen Mar 09 '16 at 15:22
  • Mostly I am confused with adding the result to volley params – Stephen Mar 09 '16 at 15:24
  • what is params? you don't need it, if you want that json you'll have to create it as I said. then you pass this variable to the right parameter of a volley request – user3290180 Mar 09 '16 at 16:42
0
 @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/x-www-form-urlencoded");
            return params;
        }
    };

this is to attache Headers with volley during a get/post request. This should be the token that facebook have provided you as response, when you tried to login through facebook login in your android application.

consider this, you will get a token like this for successful login.

token = "xyz" After successful login you have to attach this token with header on every request you make. This is identified at server end. So don't send a empty header. It should be something like this.

 @Override
        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String,String> params = new HashMap<String, String>();
            params.put("token","bearer + " " +yourtoken)
             return params;
        }
    };

Give it a try.

HourGlass
  • 1,805
  • 1
  • 15
  • 29