如何使用JAVA中的URLConnection获取带有登录信息的html文件

时间:2014-04-02 02:29:41

标签: java authentication urlconnection

我想下载一个html页面" http://www.slrclub.com/bbs/zboard.php?id=theme_gallery&category=6"

但它需要登录信息

我的代码附在下面

URL url = new URL("http://www.slrclub.com/bbs/zboard.php?id=theme_gallery&category=6");
URLConnection connection = url.openConnection();

connection.setRequestProperty("Referer", "http://www.slrclub.com/");
String name = "myid";
String password = "mypass";

String authString = name + ":" + password;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(authString.getBytes());

connection.setRequestProperty ("Authorization", basicAuth);
connection.setConnectTimeout(30000);

InputStream is_img = connection.getInputStream();


OutputStream os_img = new BufferedOutputStream(new FileOutputStream( "1.html"));



for (int b; (b = is_img.read()) != -1;) {

    os_img.write(b);

}
os_img.close();

is_img.close();

但它无效

我该怎么办?

2 个答案:

答案 0 :(得分:0)

删除该身份验证代码并安装java.net.Authenticator

答案 1 :(得分:-1)

此问题与“HTTP授权”

无关

www.slrclub.com没有使用HTTP授权。

使用浏览器Web开发工具确定网站通过网络浏览器登录时所使用的机制...并尝试让客户端采取相同的行为。

登录页面:slrclub.com/login/process.php 方法:POST 参数:user_id,密码