In my app I make HTTP calls to a web service over HTTPS. My desire is to design my client in such a way that it only asks the user for their username and password when there is an authentication challenge. I want to be reactive, not preemptive. Due to the nature of my app, there are certain cases where it would not need to authenticate.
In iOS, this process is made very easy via the NSURLConnectionDelegateProtocol, which is implemented in the iOS version of my app. A connection is made using this class, and only when a challenge is presented does the class asks its delegate for authentication credentials.
How can this be done in Android? Using the AuthenticationHandler? Or perhaps the Authenticator? If so, could can example or tutorial be provided?
Edit 1:
Using the Authenticator class (see my answer below) I am now able to respond to authentication challenges, but currently only with hard-coded credentials. I want to prompt the user for a username and password. According to the Android documentation, within the getPasswordAuthentication
method you "usually prompt the user for required input".
How is this possible? Without blocking the UI thread, which I know cannot/should-not be done, how can you display a dialog, wait for user input, then retrieve the entered credentials and return them, all within that method?
Edit 2:
While there are little or no examples on the use of the Authenticator class, what I have been able to find suggests that prompting the user for input is impossible from within a single method, like getPasswordAuthentication
. Might have to revert to the Apache Http client...
Final Edit:
I am still using HttpURLConnection, but doing something along the lines of what Edward suggested below. There doesn't seem to be any configurable class for handling authentication challenges and prompting the user for input, so I am doing this manually.