Created
April 25, 2012 07:32
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add the following to prevent errors of this kind:
Invalid use of BasicClientConnManager: connection still allocated