searchbox-io/Jest — pull request #116 by hlassiege (2014-04-23 17:11:38+00:00)
Title: Set HttpClientContext to HttpClientConfig to be able to use preemptive basic authentication

I use it that way to set a basic authentication :

@Bean
public HttpClientConfig clientConfig() throws MalformedURLException {
HttpClientConfig clientConfig = new HttpClientConfig.Builder(uri)
.multiThreaded(true)
.maxTotalConnection(500)
.defaultMaxTotalConnectionPerRoute(100)
.context(getHttpClientContext())
.build();

return clientConfig;
}

private HttpClientContext getHttpClientContext() throws MalformedURLException {
// method to perform preemptive basic authentication : see http://www.baeldung.com/httpclient-4-basic-authentication
URL url = new URL(uri);
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));

AuthCache authCache = new BasicAuthCache();
authCache.put(targetHost, new BasicScheme());

// Add AuthCache to the execution context
final HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
return context;
}

@Bean
public JestClient jestClient() throws MalformedURLException {
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(clientConfig());
return factory.getObject();
}