DS-8632N-I16-V2调用/ISAPI/System/deviceInf时,digest认证的Java
时间: 2023-12-19 20:04:01 浏览: 159
以下是使用Java进行DS-8632N-I16-V2的digest认证的示例代码:
```java
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import org.apache.commons.codec.binary.Base64;
public class DigestAuthentication {
private static String username = "admin";
private static String password = "password";
private static String host = "192.168.1.100";
private static int port = 80;
private static String realm = "";
private static String nonce = "";
private static String qop = "";
private static String algorithm = "MD5";
private static String opaque = "";
public static void main(String[] args) {
try {
// 发送GET请求获取realm、nonce等参数
HttpURLConnection connection = (HttpURLConnection) new URL("http://" + host + ":" + port).openConnection();
connection.setRequestMethod("GET");
connection.connect();
String authenticate = connection.getHeaderField("WWW-Authenticate");
if (authenticate != null && authenticate.startsWith("Digest")) {
Scanner scanner = new Scanner(authenticate.substring(7));
scanner.useDelimiter(", ");
while (scanner.hasNext()) {
String[] pair = scanner.next().split("=");
if (pair.length == 2) {
String name = pair[0].substring(1, pair[0].length() - 1);
String value = pair[1].substring(1, pair[1].length() - 1);
if ("realm".equals(name)) {
realm = value;
} else if ("nonce".equals(name)) {
nonce = value;
} else if ("qop".equals(name)) {
qop = value;
} else if ("algorithm".equals(name)) {
algorithm = value;
} else if ("opaque".equals(name)) {
opaque = value;
}
}
}
}
connection.disconnect();
// 发送POST请求进行认证
String ha1 = md5sum(username + ":" + realm + ":" + password);
String ha2 = md5sum("GET:/ISAPI/System/deviceInfo");
String response = md5sum(ha1 + ":" + nonce + ":" + "00000001" + ":" + "xyz" + ":" + qop + ":" + ha2);
connection = (HttpURLConnection) new URL("http://" + host + ":" + port + "/ISAPI/System/deviceInfo").openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Digest username=\"" + username + "\", realm=\"" + realm + "\", nonce=\"" + nonce + "\", uri=\"/ISAPI/System/deviceInfo\", qop=" + qop + ", algorithm=" + algorithm + ", opaque=\"" + opaque + "\", nc=00000001, cnonce=\"xyz\", response=\"" + response + "\"");
connection.setDoOutput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
String result = new Scanner(inputStream).useDelimiter("\\A").next();
System.out.println(result);
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String md5sum(String text) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text.getBytes());
byte[] digest = md.digest();
return Base64.encodeBase64String(digest);
}
}
```
请根据实际情况修改代码中的用户名、密码、主机名、端口号等参数。注意,要使用Apache Commons Codec库中的Base64类进行Base64编码。
阅读全文