0

我有一個solr服務器,我在web.xml中使用摘要身份驗證來保護,我需要從java調用solr。 今天我讀了很多線程,做了很多例子,但沒有運氣。apache httpcomponents摘要身份驗證失敗,舊的httpclient工作

我有這個代碼與commons-httpclient 3.1工作,我得到200 OK。

URL url = new URL(solrUrl); 

    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager()); 
    httpClient.getState().setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_SCHEME), 
      new UsernamePasswordCredentials(user, password)); 

    HttpMethod method = new GetMethod(solrUrl); 
    int responseCode = httpClient.executeMethod(method); 
    System.out.println(responseCode); 

但是當我嘗試用apache httpcomponent來做4.2.2我總是得到401未經授權的。 這與官方的例子幾乎相同。

 DefaultHttpClient httpclient = null; 
    try 
    { 
     URL url = new URL(solrUrl); 
     HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); 
     httpclient = new DefaultHttpClient(); 
     UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); 
     httpclient.getCredentialsProvider().setCredentials(
       new AuthScope(targetHost.getHostName(),targetHost.getPort()), 
       creds); 


     HttpGet httpget = new HttpGet(solrUrl); 
     HttpResponse response = httpclient.execute(targetHost,httpget); 
     HttpEntity entity = response.getEntity(); 
     System.out.println(response.getStatusLine()); 
     EntityUtils.consume(entity); 

     httpget.releaseConnection(); 


    } catch (ClientProtocolException e) 
    { 
     e.printStackTrace(); 
    } catch (IOException e) 
    { 
     e.printStackTrace(); 
    } finally 
    { 
     httpclient.getConnectionManager().shutdown(); 
    } 

我也試着用HttpUrlConnection來做,並得到相同的401 allways。

Authenticator authenticator = new Authenticator() 
    { 
     protected PasswordAuthentication getPasswordAuthentication() 
     { 
      PasswordAuthentication pa = new PasswordAuthentication(user, password.toCharArray()); 
      System.out.println("calling solr with user:pass " + pa.getUserName() + ":******"); 
      return pa; 
     } 
    }; 

    Authenticator.setDefault(authenticator); 
    try 
    { 
     URL url = new URL(solrUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setRequestMethod("GET"); 
     conn.setRequestProperty("type", "submit"); 
     conn.setDoOutput(true); 

     conn.connect(); 
    System.out.println(conn.getResponseCode()); 


     conn.disconnect(); 
    } catch (MalformedURLException mue) 
    { 
     mue.printStackTrace(); 
    } catch (IOException ioe) 
    { 
     ioe.printStackTrace(); 
    } catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

我想用,因爲類路徑的問題阿帕奇httpcomponents 4,我在放棄的過程..

任何幫助嗎?

回答

1

回答我的自我: 顯然,我已經打了JDK + Tomcat的錯誤的組合:

java bug

tomcat bug

它的發生與JDK 1.6.0_45-B06和Tomcat 7.0.34 ,把tomcat升級到7.0.41就修好了。

+0

謝謝。過去兩天我一直強調這一點,我需要的只是獲得最新的tomcat。 – hajime