2011-12-29 152 views
6

我有一個運行在Tomcat 6中的Java webapp,它從遠程URL加載RSS提要。Java代理身份驗證

我用Rome處理RSS源和不同格式的我。連接部分看起來像這樣:

try{ 
    feedSource = new URL(rssObject.getAsset()); 
}catch(MalformedURLException mue){ 
    logger.error(...); 
    throw mue; 
} 

try{ 
    URLConnection connection = feedSource.openConnection(); 
    feed = new SyndFeedInput().build(new XmlReader(connection)); 
}catch(Exception){handle...} 

的代碼工作正常,但在這個新的客戶,他們使用代理。

爲了使用代理,我設置http.proxyHost和proxyPort系統屬性:

System.setProperty("http.proxyHost", proxyHost); 
System.setProperty("http.proxyPort", proxyPort); 
System.setProperty("https.proxyHost", proxyHost); 
System.setProperty("https.proxyPort", proxyPort); 

HTTP GET是對代理製作好的,但現在我得到一個HTTP 502錯誤(壞網關或相似的東西)。

分析使用Wireshark的HTTP交換,我注意到,代理需要驗證。它發送一個HTTP 507. Java以某種方式嘗試進行身份驗證,但它使用了錯誤的用戶名和密碼。它似乎使用主機名作爲用戶名,至於我不知道的密碼。

於是,我就實現指定用戶名+密碼的身份驗證方法:

Authenticator.setDefault(new Authenticator() { 
      @Override 
      protected PasswordAuthentication getPasswordAuthentication() { 
       logger.info(MessageFormat.format("Generating PasswordAuthentitcation for proxy authentication, using username={0} and password={1}.", username, password)); 
       return new PasswordAuthentication(username, password.toCharArray()); 
      } 
     }); 

現在我的問題是,它會被忽略。 getPasswordAuthentication方法永遠不會被調用。我沒有看到日誌文件中的日誌語句,並使用Wireshark,我可以看到它仍然使用主機名作爲用戶名。

爲什麼?看起來java不知怎麼的嘗試自己進行身份驗證,而沒有諮詢Authenticator。

代理似乎是使用NTLM用於認證的MS設備。在java中有一些內置的機制來處理這個問題嗎?運行該應用程序的機器是Win Server 2008 R2。

回答

12

我們在這裏做了同樣的基於NTLM的代理進行身份驗證。

代理上的身份驗證實際上是一種正常的HTTP基本驗證

我們使用以下方法:

protected URLConnection newURLConnection(URL pURL) throws IOException { 
    URLConnection urlConnection = super.newURLConnection(pURL); 

    String auth = new String(Base64.base64Encode(new String("username:password").getBytes())); 
    auth = "Basic " + auth; 
    urlConnection.setRequestProperty("Proxy-Connection","Keep-Alive"); 
    urlConnection.setRequestProperty("Proxy-Authorization",auth); 
    return urlConnection; 
} 

也就是說,與代理JVM設置在一起,並獲得成功。

http://en.wikipedia.org/wiki/Basic_access_authentication

+0

非常感謝。它也適用於我們。 – 2011-12-29 16:05:36