HttpURLConnection模拟用户登陆

这个话题网上搜一下一大把,大致的方法如下:

URL url = new URL("网页");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 允许连接提交信息
connection.setRequestMethod("POST");// 网页提交方式“GET”、“POST”
String content = "username=admin&password=admin";
connection.setRequestProperty("Cookie", responseCookie);// 有网站需要将当前的session id一并上传
OutputStream os = connection.getOutputStream();
os.write(content.toString().getBytes("GBK"));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseCookie = connection.getHeaderField("Set-Cookie");// 取到所用的Cookie
String sessionIdString = "";
if (responseCookie != null) {
    sessionIdString = responseCookie.substring(0, responseCookie.indexOf(";"));
}
// 输出内容
String line = br.readLine();
while (line != null) {
    System.out.println(line);
    line = br.readLine();
}
// access
URL url1 = new URL("网页的登录后的页面");
HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestProperty("Cookie", responseCookie);// 给服务器送登录后的cookie
BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
String line1 = br1.readLine();
while (line1 != null) {
    // TODO:操作
}

 

有的朋友如果试了,不能在登陆以后访问其他网页,可以尝试在模拟登陆的时候连当前的Session ID一并发给服务器,试试。不过如果网站用了网页的Token机制,也就是说每个页面都会产生一个唯一键值,而且再加上登录的验证码的过程,那么上面的程序就会遇到相关困难了。

另外,HttpClient应该处理类似功能起来会容易些。

posted on 2012-02-11 18:38  山上明月  阅读(21923)  评论(0编辑  收藏  举报