当页面需要登录时,如何在 Java 中下载 HTML 源代码?

How to download HTML source in Java when the page requires a sign in?

目前我正在尝试使用 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://Username:Password@domain

我目前在使用上面的代码时遇到此错误

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

对于如何使用我的凭据对域进行身份验证以便我可以下载页面源代码的任何见解,我将不胜感激。

非常感谢 - 詹姆斯

感谢 Ale Sanchez 指向身份验证的指针 headers,我进入邮递员以探测我正在访问的域,发现它使用的是 NTLM 身份验证而不是基本身份验证。

我发现了这个网站 here,它提供了一些在 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);
}

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

-詹姆斯