Solr Change CommonsHttpSolrServer To HttpSolrServe

2019-02-10 10:03发布

问题:

For Basic Authentication in solr 3.5 I am using the following code,

String url = "http://192.168.192.11:8080/solr/FormResponses";
CommonsHttpSolrServer server = new CommonsHttpSolrServer( url );
String username = "user";
String password = "user123";
Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
server.getHttpClient().getState().setCredentials(AuthScope.ANY, defaultcreds);
server.getHttpClient().getParams().setAuthenticationPreemptive(true);

In solr 4.0 CommonsHttpSolrServer is not available, so I want to replace it with HttpSolrServer. Can anyone help me to fix this?

回答1:

Change the code as follows :

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.solr.client.solrj.impl.HttpSolrServer;

String url = "http://192.168.192.11:8080/solr/FormResponses";
HttpSolrServer server = new HttpSolrServer( url );
DefaultHttpClient client = (DefaultHttpClient) server.getHttpClient();

UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials("user", "user123");
client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);

For server.getHttpClient().getParams().setAuthenticationPreemptive(true) in HttpClient 4 you can use the solution described here.



回答2:

Finally I find the answer my self,

String url = "http://192.168.192.11:8080/solr/FormResponses";
DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(
    AuthScope.ANY, new UsernamePasswordCredentials("user", "user123"));
SolrServer solrServer = new HttpSolrServer(url, httpclient);


回答3:

You need to add the JAR solr-solrj-4.0.0.jar for HttpClientUtil .

Then use below code :

HttpSolrServer solrServer = new HttpSolrServer("http://localhost:8080/solr/"+url);     
HttpClientUtil.setBasicAuth((DefaultHttpClient) solrServer.getHttpClient(),
                            "USERNAME", "PASSWORD");

That worked for me.



回答4:

This is the only way that works for me:

String url = "192.168.192.11:8080/solr/FormResponses";
String username = "user";
String password = "user123";
HttpSolrServer server = new HttpSolrServer("http://" + username + ":" + password + "@" + url);


标签: solr solrj