Making an HTTP request for a protected resource
In this recipe, we will look at invoking an HTTP resource that has been protected by user credentials. http://httpbin.org/basic-auth/user/passwd has been protected by HTTP basic authentication. Basic authentication requires a username and a password to be provided in plain text, which is then used by the HTTP resources to decide whether the user authentication is successful.Â
If you open http://httpbin.org/basic-auth/user/passwd in the browser, it will prompt you for the username and password:
Enter the username as user
and password as passwd
, and you will be authenticated to be shown a JSON response:
{ "authenticated": true, "user": "user" }
Let's achieve the same thing using the HttpClient
API.
Â
How to do it...
- We need to extend
java.net.Authenticator
and override itsgetPasswordAuthentication()
method. This method should return an instance ofjava.net.PasswordAuthentication
. Let's create a class,ÂUsernamePasswordAuthenticator
, which extends...