下面列出了org.apache.http.impl.client.BasicCredentialsProvider#setCredentials() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void setupProxyAuth(ProxyConfiguration proxy, HttpClientBuilder clientBuilder, HttpHost proxyHost)
{
String username = proxy.getUserName();
String password = proxy.getPassword();
// Consider it to be passed if username specified. Sufficient?
if (username != null && !username.isEmpty())
{
logger.info("Using proxy authentication (user=" + username + ")");
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(
new org.apache.http.auth.AuthScope(proxyHost.getHostName(), proxy.port),
new org.apache.http.auth.UsernamePasswordCredentials(username, password));
clientBuilder.setDefaultCredentialsProvider(basicCredentialsProvider);
}
}
public CMODataAbapClient(String endpoint, String user, String password) throws URISyntaxException {
this.endpoint = new URI(endpoint);
this.requestBuilder = new TransportRequestBuilder(this.endpoint);
// the same instance needs to be used as long as we are in the same session. Hence multiple
// clients must share the same cookie store. Reason: we are logged on with the first request
// and get a cookie. That cookie - expressing the user has already been logged in - needs to be
// present in all subsequent requests.
CookieStore sessionCookieStore = new BasicCookieStore();
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(
new AuthScope(this.endpoint.getHost(), this.endpoint.getPort()),
new UsernamePasswordCredentials(user, password));
this.clientFactory = new HttpClientFactory(sessionCookieStore, basicCredentialsProvider);
}
public static CloseableHttpClient createClient(String username, String password) {
HttpClientBuilder builder = HttpClientBuilder.create();
if (username != null && password != null) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(username, password));
builder.setDefaultCredentialsProvider(credentialsProvider);
}
return builder.build();
}
private void setupCredentialsProvider() {
credentialsProvider = new BasicCredentialsProvider();
if (proxy != null) {
if (!isEmpty(proxy.getUsername()) && !isEmpty(proxy.getPassword())) {
credentialsProvider.setCredentials(
new AuthScope(proxy.getHttpHost()),
new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
}
}
}
private CredentialsProvider getProxyCredentialProvider() {
String proxyHost = Settings.getProperty("davmail.proxyHost");
int proxyPort = Settings.getIntProperty("davmail.proxyPort");
// proxy authentication
String proxyUser = Settings.getProperty("davmail.proxyUser");
String proxyPassword = Settings.getProperty("davmail.proxyPassword");
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
AuthScope authScope = new AuthScope(proxyHost, proxyPort, AuthScope.ANY_REALM);
credentialsProvider.setCredentials(authScope, new UsernamePasswordCredentials(proxyUser, proxyPassword));
return credentialsProvider;
}
public HttpClientConfigurer basicAuthCredentials(String username, String password) {
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
useBasicAuth = true;
return this;
}
public ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration, boolean trustSelfSignedCerts) {
HttpClientBuilder httpClientBuilder = HttpClients.custom()
.useSystemProperties();
if (trustSelfSignedCerts) {
httpClientBuilder.setSslcontext(buildSslContext());
httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}
if (httpProxyConfiguration != null) {
HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort());
httpClientBuilder.setProxy(proxy);
if (httpProxyConfiguration.isAuthRequired()) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(httpProxyConfiguration.getProxyHost(),
httpProxyConfiguration.getProxyPort()),
new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),
httpProxyConfiguration.getPassword()));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
httpClientBuilder.setRoutePlanner(routePlanner);
}
HttpClient httpClient = httpClientBuilder.build();
return new HttpComponentsClientHttpRequestFactory(httpClient);
}
/**
* Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND
* {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}.
*
* Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed
* certificates.
*
* @param restTemplate Must not be null
* @param username Can be null
* @param password Can be null
* @param skipSslValidation Use with caution! If true certificate warnings will be ignored.
*/
public static void prepareRestTemplate(
RestTemplate restTemplate,
String username,
String password,
boolean skipSslValidation) {
Assert.notNull(restTemplate, "The provided RestTemplate must not be null.");
final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
if (StringUtils.hasText(username) && StringUtils.hasText(password)) {
final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(
username,
password));
httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
if (skipSslValidation) {
httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext());
httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
}
final CloseableHttpClient httpClient = httpClientBuilder.build();
final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
restTemplate.setRequestFactory(requestFactory);
}
@Override
protected HttpHost determineProxy(HttpHost host, HttpRequest request, HttpContext context) throws HttpException {
HttpClientContext httpClientContext = HttpClientContext.adapt(context);
Proxy proxy = proxyPlanner.determineProxy(host, request, context, ipPool, crawlerSession);
if (proxy == null) {
return null;
}
if (log.isDebugEnabled()) {
log.debug("{} 当前使用IP为:{}:{}", host.getHostName(), proxy.getIp(), proxy.getPort());
}
context.setAttribute(VSCRAWLER_AVPROXY_KEY, proxy);
crawlerSession.setExtInfo(VSCRAWLER_AVPROXY_KEY, proxy);
if (proxy.getAuthenticationHeaders() != null) {
for (Header header : proxy.getAuthenticationHeaders()) {
request.addHeader(header);
}
}
if (StringUtils.isNotEmpty(proxy.getUsername()) && StringUtils.isNotEmpty(proxy.getPassword())) {
BasicCredentialsProvider credsProvider1 = new BasicCredentialsProvider();
httpClientContext.setCredentialsProvider(credsProvider1);
credsProvider1.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()));
}
return new HttpHost(proxy.getIp(), proxy.getPort());
}
@Override
public void applyTo(HttpClientConfig.Builder builder) {
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(username, password)
);
builder.credentialsProvider(basicCredentialsProvider);
}
@Override
public void applyTo(HttpClientFactory.Builder builder) {
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
basicCredentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(username, password)
);
builder.withDefaultCredentialsProvider(basicCredentialsProvider);
}
private BasicCredentialsProvider getCredentialsProvider() {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
if (userName != null && !userName.isEmpty() && password != null && !password.isEmpty()) {
credentialsProvider.setCredentials(AuthScope.ANY, getCredentials());
}
return credentialsProvider;
}
protected void setAuthentication(Map<String, Object> parameters, HttpClientBuilder clientBuilder)
{
String username = getUsername(parameters);
if (username != null)
{
String password = getPassword(parameters);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//FIXME proxy authentication?
credentialsProvider.setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(username, password));
clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
}
@Test
public void testFcmClientWithProxySettings() throws Exception {
// Create Settings:
IFcmClientSettings settings = new FakeFcmClientSettings();
// Define the Credentials to be used:
BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
// Set the Credentials (any auth scope used):
basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("your_username", "your_password"));
// Create the Apache HttpClientBuilder:
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create()
// Set the Proxy Address:
.setProxy(new HttpHost("your_hostname", 1234))
// Set the Authentication Strategy:
.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
// Set the Credentials Provider we built above:
.setDefaultCredentialsProvider(basicCredentialsProvider);
// Create the DefaultHttpClient:
DefaultHttpClient httpClient = new DefaultHttpClient(settings, httpClientBuilder);
// Finally build the FcmClient:
try(IFcmClient client = new FcmClient(settings, httpClient)) {
// TODO Work with the Proxy ...
}
}
private CredentialsProvider getCredentialsProvider() {
if (StringUtils.isEmpty(elasticSearchConfig.getUsername())
|| StringUtils.isEmpty(elasticSearchConfig.getPassword())) {
return null;
}
credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(elasticSearchConfig.getUsername(),
elasticSearchConfig.getPassword()));
return credentialsProvider;
}
private static HttpClient buildSpengoHttpClient() {
HttpClientBuilder builder = HttpClientBuilder.create();
Lookup<AuthSchemeProvider> authSchemeRegistry
= RegistryBuilder.<AuthSchemeProvider>create().register(
AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();
builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public String getPassword() {
return null;
}
});
builder.setDefaultCredentialsProvider(credentialsProvider);
// Avoid output WARN: Cookie rejected
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
.build();
builder.setDefaultRequestConfig(globalConfig);
CloseableHttpClient httpClient = builder.build();
return httpClient;
}
private String post(final String url) {
final BasicCredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(FEDORA_USERNAME, FEDORA_PASSWORD));
final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
try {
final HttpPost httppost = new HttpPost(url);
final HttpResponse response = httpclient.execute(httppost);
assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (final IOException ex) {
LOGGER.debug("Unable to extract HttpEntity response into an InputStream: ", ex);
return "";
}
}
private String post(final String url) {
final BasicCredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(FEDORA_USERNAME, FEDORA_PASSWORD));
final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
try {
final HttpPost httppost = new HttpPost(url);
final HttpResponse response = httpclient.execute(httppost);
assertEquals(SC_CREATED, response.getStatusLine().getStatusCode());
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (final IOException ex) {
LOGGER.debug("Unable to extract HttpEntity response into an InputStream: ", ex);
return "";
}
}
public static void setBasicAuth(String username, String password) {
provider = new BasicCredentialsProvider();
provider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(username,password));
}
private CredentialsProvider getCredentialProvider(String uid, String password) {
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials( new AuthScope( httpHost,Integer.valueOf( httpPort )),
new UsernamePasswordCredentials(uid==null? httpUid :uid,password==null? httpPw :password) );
return credentialsProvider;
}