2012-12-21 45 views
4

的基本身份驗證在Solr的3.5我使用下面的代碼,Solr的變化CommonsHttpSolrServer要HttpSolrServer

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); 

在Solr的4.0 CommonsHttpSolrServer是不可用的,所以我想用 HttpSolrServer來取代它。任何人都可以幫我解決這個問題嗎?

+1

這是什麼問題?而不是CommonsHttpSolrServer只是使用HttpSolrServer。 –

+0

@parvin CommonsHttpSolrServer不在solrj4.jar中,所以我需要一個使用HttpSolrServer而不是CommonsHttpSolrServer的新方法。 – Antguider

+0

@parvin在HttpSolrServer中getHttpClient()方法不可用 – Antguider

回答

2

最後,我找到了答案我自己,

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); 
7

更改代碼如下:

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); 

對於server.getHttpClient().getParams().setAuthenticationPreemptive(true)在HttpClient的4可以使用溶液描述here

+0

這表明java.lang.ClassCastException:org.apache.http.impl.client.DefaultHttpClient不能轉換到org.apache.commons.httpclient.HttpClient ---燦你爲你的效果提供你的進口陳述 – Antguider

+2

+1。謝謝,最後我找到了解決方案本身 – Antguider

1

您需要添加JAR solr-solrj-4.0.0.jar的HttpClientUtil。

然後使用下面的代碼:

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

爲我工作。

+0

這適用於讀取操作,但不適用於solr寫入(因爲連接不是搶先式的) – Mani

1

這是對我的作品的唯一途徑:

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