2010-11-25 60 views
1

我正在實施單點登錄功能,以使用摘要式身份驗證自動登錄到關聯的https網站。目前,我的代碼是使用URLConnection的摘要式身份驗證

URL url = new URL(protocol, ip, port, path); 
URLConnection connection = url.openConnection(Proxy.NO_PROXY); 
connection.connect(); 

if (connection != null && connection.getHeaderFields() != null) { 
    if (connection.getHeaderFields().get(AUTHENTICATE_RESPONSE_HEADER) != null) { 
     Map<String, String> authenticateParameters = identifyAuthentication(connection); 

     String ha1 = calculateMD5(username + ":" + authenticateParameters.get("realm") + ":" + password); 
     String ha2 = calculateMD5("GET" + ":" + path); 
     String response = calculateMD5(ha1 + ":" + 
      authenticateParameters.get("nonce") + ":" + 
      "00000001" + ":" + 
      authenticateParameters.get("qop") + ":" + 
      ha2); 

      String authorizationRequest = authenticateParameters.get("challenge") + " " + 
        "username=" + username + ", " + 
        "realm=" + authenticateParameters.get("realm") + ", " + 
        "nonce=" + authenticateParameters.get("nonce") + ", " + 
        "uri=" + path + ", " + 
        "qop=" + authenticateParameters.get("qop") + ", " + 
        "nc=" + "00000001" + ", " + 
        "response=" + response + ", " + 
        "opaque=" + authenticateParameters.get("opaque"); 

      connection.setAllowUserInteraction(true); 
      connection.addRequestProperty(AUTHENTICATION_REQUEST_PROPERTY, authorizationRequest); 
      connection.getHeaderFields(); 
    } 
} 

的問題是,我得到

java.lang.IllegalStateException: Already connected 
    at java.net.URLConnection.addRequestProperty(URLConnection.java:1061) 
    at sun.net.www.protocol.http.HttpURLConnection.addRequestProperty(HttpURLConnection.java:2016) 
    at com.ibm.net.ssl.www2.protocol.https.a.addRequestProperty(a.java:49) 

它,我想,是有道理的,但並不能幫助我。我將如何去創建一個請求/響應登錄在這裏(並最終得到一個sessionId)?

在此先感謝。

+0

我們可以看到完整的堆棧跟蹤?我不確定您的方法中哪條線路發生故障。 – 2010-11-25 16:22:11

+0

補充 - 感謝您抽出時間。 – heeboir 2010-11-25 16:41:32

回答

5

當連接請求標頭已經連接(您已經發送請求標頭)時,您無法修改它。您必須爲第二個請求建立新的連接。

E.g.

connection = url.openConnection(Proxy.NO_PROXY); 
connection.addRequestProperty(AUTHENTICATION_REQUEST_PROPERTY, authorizationRequest); 
connection.getHeaderFields(); 

然後,您可以從頭中獲取sessionId或cookie。

這可能是更容易使用Apache的HttpClient文摘能力:http://hc.apache.org/httpclient-3.x/authentication.html