hee*_*oir 1 java urlconnection digest-authentication
我正在实施单点登录功能,以使用摘要式身份验证自动登录到附属的https网站.目前我的代码是
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();
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我得到了
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)
Run Code Online (Sandbox Code Playgroud)
我想这对我有意义,但对我没有帮助.我如何创建一个登录请求/响应(最终获得sessionId)?
提前致谢.
连接请求标头已经连接时(您已经发送了请求标头),您无法修改它.您必须为第二个请求建立新连接.
例如
connection = url.openConnection(Proxy.NO_PROXY);
connection.addRequestProperty(AUTHENTICATION_REQUEST_PROPERTY, authorizationRequest);
connection.getHeaderFields();
Run Code Online (Sandbox Code Playgroud)
然后,您可以从标头中获取sessionId或更确切地说cookie.
使用apache HttpClient的摘要功能可能更容易:http://hc.apache.org/httpclient-3.x/authentication.html
归档时间: |
|
查看次数: |
5886 次 |
最近记录: |