0

my application wants to check whether the user's login credentials are valid to access the web API. To do so, I have implemented this with AsyncTask method.

Here is doInBackground() implementation.

protected Boolean doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
        URL url = null;
        try {
            url = new URL(params[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setConnectTimeout(1000);
            urlConnection.setReadTimeout(1000);
            Authenticator.setDefault (new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication (user, password.toCharArray());
                }
            });

            return (HttpURLConnection.HTTP_OK == urlConnection.getResponseCode());
        } catch (SocketTimeoutException e) {
        } catch (IOException e){
        }
        return false;
    }

When I enter the right user credentials, it would work fine. However, when I enter the wrong credentials, it would stay hanging at urlConnection.getResponseCode() (does not throw any exception). I tried to add urlConnection.connect() in between, but I found no success. I have internet access set up in manifest.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • have you checked that the server properly handles incorrect credentials? (ex. returning an error response) – Gino Mempin Oct 27 '16 at 23:28
  • @ginomempin When I cURL the api data with incorrect credentials, instead of getting JSON value, it returns html code -> Error 401

    HTTP ERROR: 401

    Problem accessing /webapi/v1/hosts. Reason:

        Unauthorized

    Powered by Jetty://
    – Cike Eministav Oct 28 '16 at 15:23
  • first off, i think your request method should be **POST**. next, my guess is that's the old issue with `Authenticator` (which I recommend to avoid using). try putting your username,password credentials directly into the HTTP request property as answered [here](http://stackoverflow.com/q/14572099/2745495) and [here](http://stackoverflow.com/a/16359106/2745495). – Gino Mempin Oct 29 '16 at 03:14

0 Answers0