![](/img/trans.png)
[英]JAVA: How can I download an HTML file from a site that requires cookies enabled?
[英]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中,但未使用。
我在使用上面的代碼時出現此錯誤
java.io.IOException: Server returned HTTP response code: 401 for URL:
我非常感謝有關如何使用我的憑據對域進行身份驗證的任何見解,以便我可以下載頁面源。
非常感謝 - 詹姆斯
感謝Ale Sanchez指向身份驗證標頭的指針,我進入郵遞員來探測我正在攻擊的域名,發現它使用的是NTLM身份驗證而不是基本身份驗證。
我在這里遇到了這個網站,它提供了一些在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);
}
感謝所有評論他們幫助的人:)
-詹姆士
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.