Okhttp provides support for user authentication. When the status code for the HTTP response is 401, okhttp gets the new request object from the Set authenticator object and attempts to make the request again. The Authenticate method in the authenticator interface is used to provide a request object for authentication, and the Authenticateproxy method is used to provide a request object that authenticates the proxy server.
Examples of user authentication:
Okhttpclient client = new Okhttpclient ();
Client.setauthenticator (New Authenticator () {public
Request authenticate (proxy proxy, Response Response) throws IOException {
String credential = credentials.basic ("User", "password");
Return Response.request (). Newbuilder ().
Header ("Authorization", credential)
. Build ();
Public Request authenticateproxy (proxy proxy, Response Response)
throws IOException {return
null;
}
} );
Advanced
when you need to implement a Basic challenge, use Credentials.basic (username, password) to encode the request headers.
Private final Okhttpclient client = new Okhttpclient (); public void Run () throws Exception {Client.setauthenticator (New authenticator () {@Override public Request Authenticat
E (proxy proxy, Response Response) {System.out.println ("Authenticating for Response:" + Response);
System.out.println ("Challenges:" + response.challenges ());
String credential = Credentials.basic ("Jesse", "Password1");
Return Response.request (). Newbuilder (). Header ("Authorization", credential). Build (); @Override public Request authenticateproxy (proxy proxy, Response Response) {return null;//null indicates no ATT
Empt to authenticate.
}
});
Request Request = new Request.builder (). URL ("Http://publicobject.com/secrets/hellosecret.txt"). Build ();
Response Response = client.newcall (Request). Execute ();
if (!response.issuccessful ()) throw new IOException ("Unexpected Code" + response);
System.out.println (Response.body (). String ()); }