我创建了一个Java类,该类连接到需要NTLM身份验证的IIS网站。 Java类使用JCIFS库,并基于以下示例:
Config.registerSmbURLHandler();
Config.setProperty("jcifs.smb.client.domain", domain);
Config.setProperty("jcifs.smb.client.username", user);
Config.setProperty("jcifs.smb.client.password", password);
URL url = new URL(location);
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
从命令提示符处执行该示例时,该示例运行良好,但是当我尝试在servlet容器(特别是GlassFish)中使用相同的代码时,我得到一个
IOException
,其中包含以下消息:“服务器返回了HTTP响应代码:URL为401 :....“。我尝试将jcifs jar移至系统类路径(%GLASSFISH%/ lib),但这似乎没有任何区别。
建议非常赞赏。
最佳答案
似乎我想做的事情已经在Java 5/6中得到支持,因此我能够删除JCIFS API并改为执行以下操作:
public static String getResponse(final ConnectionSettings settings,
String request) throws IOException {
String url = settings.getUrl() + "/" + request;
Authenticator.setDefault(new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
System.out.println(getRequestingScheme() + " authentication")
// Remember to include the NT domain in the username
return new PasswordAuthentication(settings.getDomain() + "\\" +
settings.getUsername(), settings.getPassword().toCharArray());
}
});
URL urlRequest = new URL(url);
HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");
StringBuilder response = new StringBuilder();
InputStream stream = conn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(stream));
String str = "";
while ((str = in.readLine()) != null) {
response.append(str);
}
in.close();
return response.toString();
}