首页 > 解决方案 > 当页面需要登录时,如何用 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 中,但没有成功。

http://用户名:密码@域

使用上面的代码时,我目前收到此错误

java.io.IOException: Server returned HTTP response code: 401 for URL:

我非常感谢有关如何使用我的凭据对域进行身份验证的任何见解,以便我可以下载页面源。

非常感谢 - 詹姆斯

标签: javahtmlauthenticationurlntlm

解决方案


感谢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);
}

感谢所有评论的人的帮助:)

-詹姆士


推荐阅读