1

ダイジェスト認証を使用して、関連する https Web サイトに自動的にログインするためのシングル サインオン機能を実装しています。現在、私のコードは

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 を取得する) ためのリクエスト/レスポンスを作成するにはどうすればよいですか?

前もって感謝します。

4

1 に答える 1

5

接続要求ヘッダーが既に接続されている (既に要求ヘッダーを送信している) 場合、接続要求ヘッダーを変更することはできません。2 番目のリクエストでは、新しい接続を作成する必要があります。

例えば

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

その後、ヘッダーから sessionId または Cookie を取得できます。

Apache HttpClient の Digest 機能を使用する方が簡単かもしれません: http://hc.apache.org/httpclient-3.x/authentication.html

于 2010-11-25T17:31:34.317 に答える