2011-02-03 18 views
32

我正在寫一個Java客戶端,發佈到需要身份驗證的HTTP服務器
我必須至少支持以下三種身份驗證方法:基本,摘要或協商。此外,POST可能非常大(超過2MB),所以我需要使用流媒體。 正如記載爲HttpURLConnection如何使用HttpURLConnection處理HTTP身份驗證?

When output streaming is enabled, authentication and redirection cannot be handled automatically. A HttpRetryException will be thrown when reading the response if authentication or redirection are required.

所以,我需要處理驗證自己。我搜索,並再次搜索的方式來僱用,已編碼的類 - 但沒有辦法...

我可以從here(因爲他們是GPLv2類路徑異常)採摘所需的來源。這是正確的方式嗎?

謝謝。

+0

什麼樣的認證? HTTP基本身份驗證?還是更復雜的東西? – Tim 2011-02-03 06:58:17

+0

可以是_Basic_,_Digest_或_Negotiate_。基本是**簡單**。另外兩個不是:) – Opher 2011-02-03 12:00:07

回答

47

你需要輸出流嗎? HttpURLConnection絕對支持Authenticator類的認證,請參閱:Http Authentication

更新:如果Authenticator不是一個選項,您可以通過向您的HTTP請求添加額外的標頭來手動執行HTTP基本認證。試試下面的代碼(未經測試):

String userPassword = username + ":" + password; 
String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes()); 
URLConnection uc = url.openConnection(); 
uc.setRequestProperty("Authorization", "Basic " + encoding); 
uc.connect(); 
+0

是的。我的** POST **包含一個可能超過2MB大小的文件。 – Opher 2011-02-03 12:02:38

4

相關的@墊的評論:

這是我的球隊,我用一個例子:

import org.apache.commons.codec.binary.Base64; 

HttpGet getRequest = new HttpGet(endpoint); 
getRequest.addHeader("Authorization", "Basic " + getBasicAuthenticationEncoding()); 

private String getBasicAuthenticationEncoding() { 

     String userPassword = username + ":" + password; 
     return new String(Base64.encodeBase64(userPassword.getBytes())); 
    } 

希望它能幫助!