Skip to content

Instantly share code, notes, and snippets.

@maddingo
Created April 25, 2012 07:32
Show Gist options
  • Save maddingo/2487775 to your computer and use it in GitHub Desktop.
Save maddingo/2487775 to your computer and use it in GitHub Desktop.
Solr Http Client authentication with solrj-3.6.0 and httpclient-4.1.2 (usage see https://gist.github.com/2487779)
package no.uis.service.fsimport.util;
import java.net.URL;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthCache;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicAuthCache;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
class PreemptBasicAuthHttpClient extends DefaultHttpClient {
private URL url;
public PreemptBasicAuthHttpClient(URL url, String username, String password) {
this.url = url;
BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
setCredentialsProvider(credsProvider);
}
@Override
protected HttpContext createHttpContext() {
HttpContext context = super.createHttpContext();
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
authCache.put(targetHost, basicAuth);
context.setAttribute(ClientContext.AUTH_CACHE, authCache);
return context;
}
}
@mohsen
Copy link

mohsen commented Oct 15, 2015

Add the following to prevent errors of this kind: Invalid use of BasicClientConnManager: connection still allocated

@Override
protected ClientConnectionManager createClientConnectionManager() {
    return new PoolingClientConnectionManager();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment