下面列出了怎么用org.apache.http.impl.auth.BasicSchemeFactory的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 默认是 Bsic认证机制
*
* @param ip
* @param username
* @param password
* @return
*/
public static HttpClient getHtpClient(String ip, int port, String username, String password) {
HttpHost proxy = new HttpHost(ip, port);
Lookup<AuthSchemeProvider> authProviders =
RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.build();
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
if (username != null && password != null) {
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
} else {
credsProvider.setCredentials(AuthScope.ANY, null);
}
RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
CloseableHttpClient httpClient = HttpClients
.custom()
.setConnectionManager(cm)
.setProxy(proxy)
.setRedirectStrategy(new LaxRedirectStrategy())
.setDefaultRequestConfig(requestConfig)
.setDefaultAuthSchemeRegistry(authProviders)
.setDefaultCredentialsProvider(credsProvider)
.build();
return httpClient;
}
@Override public void setUsernamePassword(AuthenticationType authType, String username,
String password) {
this.credentials = new UsernamePasswordCredentials(
Objects.requireNonNull(username), Objects.requireNonNull(password));
this.credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, credentials);
RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create();
switch (authType) {
case BASIC:
authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory());
break;
case DIGEST:
authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
break;
default:
throw new IllegalArgumentException("Unsupported authentiation type: " + authType);
}
this.authRegistry = authRegistryBuilder.build();
}
public static void initAuth(ConfigProvider configuration)
{
// Setting up BASIC and DIGEST auth
setupUserPassAuthScheme(AuthScheme.BASIC, AuthSchemes.BASIC, new BasicSchemeFactory(), configuration);
setupUserPassAuthScheme(AuthScheme.DIGEST, AuthSchemes.DIGEST, new DigestSchemeFactory(), configuration);
// Adding kerberos standard auth
setupHttpAuthScheme(AuthSchemes.KERBEROS, new KerberosSchemeFactory(), AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS);
authRegistry = registryBuilder.build();
}
private Registry<AuthSchemeProvider> getAuthSchemeRegistry() {
final RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create();
registryBuilder.register(AuthSchemes.NTLM, new JCIFSNTLMSchemeFactory())
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.register(AuthSchemes.DIGEST, new DigestSchemeFactory());
if (Settings.getBooleanProperty("davmail.enableKerberos")) {
registryBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory());
}
return registryBuilder.build();
}
public static void initAuth(ConfigProvider configuration)
{
// Setting up BASIC and DIGEST auth
setupUserPassAuthScheme(AuthScheme.BASIC, AuthSchemes.BASIC, new BasicSchemeFactory(), configuration);
setupUserPassAuthScheme(AuthScheme.DIGEST, AuthSchemes.DIGEST, new DigestSchemeFactory(), configuration);
// Adding kerberos standard auth
setupHttpAuthScheme(AuthSchemes.KERBEROS, new KerberosSchemeFactory(), AuthScope.ANY, DEFAULT_TOKEN_CREDENTIALS);
authRegistry = registryBuilder.build();
}
@Test
public void buildLookupWithBasicAuth() {
AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.BASIC);
assertThat(provider, instanceOf(BasicSchemeFactory.class));
BasicScheme basicSchema = ((BasicScheme) provider.create(null));
assertEquals("UTF-8", basicSchema.getCredentialsCharset().toString());
}
/**
* @param proxy Proxy configuration
* @param listener Log listener
* @param prompt Prompt for proxy credentials
* @return Builder for HTTP client
*/
public HttpClientBuilder build(final Proxy proxy, final TranscriptListener listener, final LoginCallback prompt) {
final HttpClientBuilder configuration = HttpClients.custom();
// Use HTTP Connect proxy implementation provided here instead of
// relying on internal proxy support in socket factory
switch(proxy.getType()) {
case HTTP:
case HTTPS:
final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), Scheme.http.name());
if(log.isInfoEnabled()) {
log.info(String.format("Setup proxy %s", h));
}
configuration.setProxy(h);
configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt));
break;
}
configuration.setUserAgent(new PreferencesUseragentProvider().get());
final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
configuration.setDefaultSocketConfig(SocketConfig.custom()
.setTcpNoDelay(true)
.setSoTimeout(timeout)
.build());
configuration.setDefaultRequestConfig(this.createRequestConfig(timeout));
configuration.setDefaultConnectionConfig(ConnectionConfig.custom()
.setBufferSize(preferences.getInteger("http.socket.buffer"))
.setCharset(Charset.forName(host.getEncoding()))
.build());
if(preferences.getBoolean("http.connections.reuse")) {
configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy());
}
else {
configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
}
configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry")));
configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy());
if(!preferences.getBoolean("http.compression.enable")) {
configuration.disableContentCompression();
}
configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener));
// Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the
// default port and the socket factory to be used to create the java.net.Socket instances for the given protocol
configuration.setConnectionManager(this.createConnectionManager(this.createRegistry()));
configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create()
.register(AuthSchemes.BASIC, new BasicSchemeFactory(
Charset.forName(preferences.getProperty("http.credentials.charset"))))
.register(AuthSchemes.DIGEST, new DigestSchemeFactory(
Charset.forName(preferences.getProperty("http.credentials.charset"))))
.register(AuthSchemes.NTLM, preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ?
new BackportWindowsNTLMSchemeFactory(null) :
new NTLMSchemeFactory())
.register(AuthSchemes.SPNEGO, preferences.getBoolean("webdav.ntlm.windows.authentication.enable") && WinHttpClients.isWinAuthAvailable() ?
new BackportWindowsNegotiateSchemeFactory(null) :
new SPNegoSchemeFactory())
.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build());
return configuration;
}
private static Lookup<AuthSchemeProvider> createAuthSchemeRegistry() {
return RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.DIGEST, new DigestSchemeFactory())
.register(AuthSchemes.BASIC, new BasicSchemeFactory())
.register(AuthSchemes.NTLM, new NTLMSchemeFactory())
.build();
}