1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| private class NtlmAuthenticator implements Authenticator, Interceptor {
private final String username;
private final String password;
public NtlmAuthenticator(final String username, final String password) {
super();
this.username = username;
this.password = password;
}
public PasswordAuthentication getPasswordAuthentication() {
System.out.println("Get password auth");
return (new PasswordAuthentication(username, password.toCharArray()));
}
@Override
public Request authenticate(final Route route, final Response response) throws IOException {
System.out.println("Get password auth");
if (responseCount(response) >= 3) {
return null; // If we've failed 3 times, give up. - in real life, never give up!!
}
final String credential = Credentials.basic(username, password);
return response.request().newBuilder().header("Authorization", credential).header("Proxy-Authorization", credential).build();
}
private int responseCount(Response response) {
int result = 1;
while ((response = response.priorResponse()) != null) {
result++;
}
return result;
}
@Override
public Response intercept(final Chain chain) throws IOException {
System.out.println("Get password auth from interceptor");
final String credential = Credentials.basic(username, password);
final Request request = chain.request();
final Request authenticatedRequest = request.newBuilder().header("Authorization", credential).build();
return chain.proceed(authenticatedRequest);
}
} |
Partager