0

I have a JSONObjectRequest I'm trying to send to my Rails app via Volley. I'm hitting my Rails API, but am getting 401 responses. My API definitely works via curl, so I think I haven't formed my Volley request quite right.

public void login(View button) {
        EditText userEmailField = (EditText) findViewById(R.id.userEmail);
        mUserEmail = userEmailField.getText().toString();
        EditText userPasswordField = (EditText) findViewById(R.id.userPassword);
        mUserPassword = userPasswordField.getText().toString();


        if (mUserEmail.length() == 0 || mUserPassword.length() == 0) {
            // input fields are empty
            Toast.makeText(this, "Please complete all the fields",
                Toast.LENGTH_LONG).show();
            return;
        } else {
            JsonObjectRequest loginRequest = new JsonObjectRequest(Request.Method.POST, url, null,
                    new Response.Listener<JSONObject>() {
                        @Override public void onResponse(JSONObject response) {
                            try {
                                //everything is good
                                if (response.getBoolean("success")) {
                                    SharedPreferences.Editor editor = mPreferences.edit();

                                //Save auth_token into shared preferences
                                    editor.putString("AuthToken", response.getJSONObject("data").getString("auth_token"));
                                    editor.commit();

                                // launch the HomeActivity and close this one
                                    Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                                    startActivity(intent);
                                    finish();

                                }

                            } catch (Exception e) {
                                // something went wrong: show Toast
                                //with the exception message
                                Toast.makeText(myActivity, e.getMessage(), Toast.LENGTH_LONG).show();
                            } 
                        }
                    },
                    new Response.ErrorListener()
                    {
                        @Override public void onErrorResponse(VolleyError error) {
                            Log.d("Error.Response", error.toString());
                        }
                    }) {

                 @Override
                 protected Map<String, String> getParams() {
                     Map<String, String> params = new HashMap<String, String>();
                     params.put("email", mUserEmail);
                     params.put("password", mUserPassword);

                     return params;
                 }
            };

            VolleySingleton.getInstance(this).addToRequestQueue(loginRequest); //Call to get dashboard feed
        }
     };

EDIT

Rails log with 401: It appears that my params aren't being included with the request. What did I do wrong in the Volley request that it wouldn't be included?

Started POST "/api/v1/sessions" for 11.111.111.11 at ....
Processing by Api::V1::SessionsController#create as JSON
Parameters: {"session"=>{}}
Completed 401 Unauthorized in 2ms
settheline
  • 3,183
  • 8
  • 28
  • 61
  • Can you post the Rails log for the 401 error – jamesc Jun 24 '14 at 01:33
  • Yep, updated with the Rails log from Heroku. – settheline Jun 24 '14 at 03:46
  • No idea. All I can suggest you do is add some log.d messages to interrogate the flow and values in the android app. Make sure what you think is happening is actually what is happening. – jamesc Jun 24 '14 at 14:24
  • I logged out my variables to make sure they were getting assigned, which they are. I think I've narrowed it to the getParams method. Could this be the problem (the second/third answer make sense although not sure if Rails handles this like PHP)?http://stackoverflow.com/questions/19760212/google-volley-ignores-post-parameter – settheline Jun 24 '14 at 16:50
  • Is the getParams() method actually being called? – jamesc Jun 24 '14 at 19:34
  • TBH, I'm not sure. Is there a way to log that? I figured it was being called as part of `loginRequest`, no? I'm very green in terms of Android dev, sorry if this is dense! – settheline Jun 24 '14 at 19:36
  • I have no idea how Volley works. Add log.d messages to the getParams method and see if they get output in logcat. Your approach to send a POST request to the sessions controller is a little odd but that is not the question here. You should be able to call whatever you want. – jamesc Jun 24 '14 at 22:45
  • According to comments here http://www.androidhive.info/2014/05/android-working-with-volley-library-1/ getParams method doesn't get called. Can you add the params to your json object? – jamesc Jun 24 '14 at 22:49
  • Personally I would use an intentservice and post using the json libraries. Check out the accepted answer here http://stackoverflow.com/questions/6218143/android-post-json-using-http – jamesc Jun 24 '14 at 22:58
  • Thanks for your help on this. I answered below after checking out the comments in that article you linked. Curious why you say it's odd to send a POST request to the sessions controller? It's calling the create action, so it seems correct no? – settheline Jun 25 '14 at 02:14

1 Answers1

0

Thanks to @jamesw for pointing me in the right direction here. For some reason, getParams is not being called in this POST Request. I'm not sure why, but apparently other people have had the same issue.

A workaround is to create a JSONObject and pass it into the JsonObjectRequest:

JSONObject parentData = new JSONObject();
JSONObject childData = new JSONObject();
  try {
    childData.put("email", mUserEmail);
    childData.put("password", mUserPassword);
    parentData.put("user", childData);
  } catch (JSONException e) {
    e.printStackTrace();
  }

Pass it into the JOR constructor:

JsonObjectRequest loginRequest = new JsonObjectRequest(Request.Method.POST, url, parentData, Listener..., ErrorListener...

Works for me, but if someone can explain how to call getParams() or a cleaner solution, feel free to answer and I'll accept.

settheline
  • 3,183
  • 8
  • 28
  • 61
  • you should use `StringRequest` instead of `JsonObjectRequest`, see my answer [here](http://stackoverflow.com/a/24402403/1294681). – VinceStyling Jun 26 '14 at 04:35