-1

I've already looked at many tutorials, but I am stumped. This is the code I have so far that I've put together from several guides:

protected Boolean doInBackground(Void... params) {
        // TODO: attempt authentication against a network service.

        try {
            // Create URL
            url = baseUrl + "signin?username=" + mEmail + "&password=" + mPassword + "&remember_me=true&accept_terms=true";

            // Next, we create a new JsonArrayRequest. This will use Volley to make a HTTP request
            // that expects a JSON Array Response.
            // To fully understand this, I'd recommend readng the office docs: https://developer.android.com/training/volley/index.html
            JsonArrayRequest arrReq = new JsonArrayRequest(Request.Method.GET, url,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray response) {
                            // Check the length of our response 
                            if (response.length() > 0) {
                                for (int i = 0; i < response.length(); i++) {
                                    try {
                                        JSONObject jsonObj = response.getJSONObject(i);
                                        String repoName = jsonObj.get("name").toString();
                                        String lastUpdated = jsonObj.get("updated_at").toString();
                                    } catch (JSONException e) {
                                        // If there is an error then output this to the logs.
                                        Log.e("Volley", "Invalid JSON Object.");
                                    }

                                }
                            } else {
                            }

                        }
                    },

                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            // If there a HTTP error then add a note to our repo list.
                            Log.e("Volley", error.toString());
                        }
                    }
            );
            // Add the request we just defined to our request queue.
            // The request queue will automatically handle the request as soon as it can.
            requestQueue.add(arrReq);
            // Simulate network access.
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            return false;
        }

        for (String credential : DUMMY_CREDENTIALS) {
            String[] pieces = credential.split(":");
            if (pieces[0].equals(mEmail)) {
                // Account exists, return true if the password matches.
                return pieces[1].equals(mPassword);
            }
        }

        // TODO: register the new account here.
        return false;
    }

The api I am trying to use is: https://neurofit.me/nfoidc/api/swagger-ui#/ I want to implement a sign in function in my app, so I want to call the signin function. I have the email and password that the user puts in, but there are other parameters like accept-language and user-agent that are called headers.

I am extremely confused as to how I can just send in the email and password and get back a JSON file. I also don't think I am constructing the URL correctly.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
Larry Jing
  • 383
  • 1
  • 5
  • 26
  • First problem is you are using a GET request for signin, per your API (correctly I might add) that should be a POST request. You will need to use a POST request and put the values as JSON in the body of the request, not in the URL – Zach Jun 19 '18 at 18:01
  • 1
    To expand on that, look at "making a post request" [here](https://www.itsalif.info/content/android-volley-tutorial-http-get-post-put) – Zach Jun 19 '18 at 18:08
  • @Zach so is my current code completely wrong? the guide looks very different to what I have – Larry Jing Jun 19 '18 at 18:36
  • It is fairly similar, the main points are using `Request.Method.POST` and overriding `getParams()` and in your case you will set the headers by overriding `getHeaders()` like [here](https://stackoverflow.com/questions/17049473/how-to-set-custom-header-in-volley-request) as well.. I will make an answer to get you going in the right direction, hold on – Zach Jun 19 '18 at 18:40
  • @Zach Ok, thank you! – Larry Jing Jun 19 '18 at 18:41

1 Answers1

1

As mentioned in my comments, you need to use a POST request and put the values as JSON in the body.

This likely isn't perfect so I was tentative to put an answer, however, it is closer to what you need to do. Someone who has used the library might be able to clean this up a bit.

protected Boolean doInBackground(Void... params) {
    try {
        JsonArrayRequest loginRequest = new JsonArrayRequest(Request.Method.POST, baseUrl, 
                new Response.Listener<JSONArray>() 
                {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d("Response", response.toString());
                        if (response.length() > 0) {
                            for (int i = 0; i < response.length(); i++) {
                                try {
                                    JSONObject jsonObj = response.getJSONObject(i);
                                    String repoName = jsonObj.get("name").toString();
                                    String lastUpdated = jsonObj.get("updated_at").toString();
                                } catch (JSONException e) {
                                    // If there is an error then output this to the logs.
                                    Log.e("Volley", "Invalid JSON Object.");
                                }

                            }
                        } else {

                        }
                    }
                }, 
                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("username", mEmail);  
                    params.put("password", mPassword);
                    params.put("remember_me", "true");
                    params.put("accept_terms", "true");
                    return params;  
            }

            @Override
            public Map<String, String> getHeaders() 
            {  
                    Map<String, String>  params = new HashMap<String, String>();  
                    params.put("Content-Type", "application/json");

                    //your api claims to require these below, but it likely  
                    //gets set by volley defaults, try without for starters
                    //then figure out what your API is looking for here if not working

                    //params.put("accept", "text/html"); 
                    //params.put("accept-language", "en-US");
                    //params.put("user-agent", "idk"); 
                    return params;  
            }
        };
        requestQueue.add(loginRequest);

    } catch (InterruptedException e) {
        return false;
    }
    return false;
}
Zach
  • 1,964
  • 2
  • 17
  • 28
  • I have 3 syntax errors, new Response.Listener(), the @override below it, and JSONObject jsonObj = response.getJSONObject(i); – Larry Jing Jun 19 '18 at 19:21
  • the Listener one says it has to be abstract and the @override literally just says it doesn't override from superclass, and the .getjsonobject doesnt exist. – Larry Jing Jun 19 '18 at 19:23
  • Okay, it was because I forgot to change the `String reponse` to a `JSONArray response` like you had before in `onResponse`. I updated it.. Like I mentioned, this won't be perfect, likely will need to do more than even just fixing the small syntax errors to get it actually working – Zach Jun 19 '18 at 19:26
  • ok, thanks. for user-agent, in cause it needs it, should I use the mozilla one on wikipedia? – Larry Jing Jun 19 '18 at 19:27
  • 1
    I assume that will get set by volley, likely won't have to worry about it. That would depend on your api and seems unlikely that it would really matter what is there – Zach Jun 19 '18 at 19:30
  • fyi, response gives an error in log.d, so I changed it to error.toString() and response.toString() – Larry Jing Jun 19 '18 at 19:30
  • @LarryJing Be very, very careful about capitalization. `getjsonobject` is NOT the same as `getJSONObject`. – Code-Apprentice Jun 19 '18 at 19:35
  • @Code-Apprentice i am new to json, not sure if I need it at all. I just want to be able to see whether or not login was successful – Larry Jing Jun 19 '18 at 19:39
  • also, getHeaders() has to be public not protected – Larry Jing Jun 19 '18 at 19:44
  • @LarryJing I'm talking about JavaScript, not JSON. Many programming languages are case-sensitive, meaning that upper and lower case letters are treated differently. As a programmer, you must train yourself to see "a" and "A" as two different things, just as different as "a" and "z". – Code-Apprentice Jun 19 '18 at 20:58