java - 当页面需要登录时,如何用 Java 下载 HTML 源代码?
问题描述
目前我正在尝试使用 URL 对象和如下所示的输入流下载网页的 html 源代码。
url = new URL(urlString));
is = url.openStream();
br = new BufferedReader(new InputStreamReader(is));
while((tempLine = br.readLine()) != null){
pageSource.append(tempLine);
}
该网页在浏览时需要用户名和密码,并且在正常浏览时出现弹出菜单,我尝试将用户名和密码以以下格式传递到 URL 中,但没有成功。
使用上面的代码时,我目前收到此错误
java.io.IOException: Server returned HTTP response code: 401 for URL:
我非常感谢有关如何使用我的凭据对域进行身份验证的任何见解,以便我可以下载页面源。
非常感谢 - 詹姆斯
解决方案
感谢Ale Sanchez提供指向 Authentication 标头的指针,我进入邮递员调查我正在访问的域,发现它使用的是 NTLM 身份验证而不是 Basic 身份验证。
我在这里遇到了这个网站,它提供了一些在 Java 中使用 NTLM 身份验证的真实示例,并使用了以下完美运行的代码
static final String kuser = "username"; // your account name
static final String kpass = password; // retrieve password for your account
static class MyAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
// I haven't checked getRequestingScheme() here, since for NTLM
// and Negotiate, the usrname and password are all the same.
System.err.println("Feeding username and password for " + getRequestingScheme());
return (new PasswordAuthentication(kuser, kpass.toCharArray()));
}
}
public static void main(String[] args) throws Exception {
Authenticator.setDefault(new MyAuthenticator());
URL url = new URL(args[0]);
InputStream ins = url.openConnection().getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins));
String str;
while((str = reader.readLine()) != null)
System.out.println(str);
}
感谢所有评论的人的帮助:)
-詹姆士
推荐阅读
- android - AdMob 永远不会在某些设备上加载
- google-maps - 谷歌静态地图不显示超过 5 个图钉
- sql - SQL从两个表中选择数据并按点排序
- python - ValueError:系列的真值不明确 - 检查数据帧值是否等于字符串时
- javascript - FOR循环:如果我在FOR循环中看到两个initialExpression,js是什么意思?
- java - 跨所有方法的单一连接
- android - 当我处于夜间模式时,背景警报对话框保持白色
- php - 无法使用 PHP-FPM 连接到 MySQL 数据库
- flutter - 使用 pdf 查看器脚手架在颤振中动态打开 PDF
- java - TreeItem 在 JavaFX 中被覆盖。如何解决这个问题?