在WebClient类中保持Session

    今天帮一个朋友写投票机程序,使用了WebClient类,但是因为整个投票过程不是一次点击就可以完成的,过程大致如下:
    首先要提交一个类似注册的链接,然后再提交一个过渡链接,并根据过渡链接返回页面数据中的一个含随机数的链接做出投票提交。在整个过程中需要保持Session。
    一开始直接使用WebClient的DownloadString方法来达到点击效果,并获取页面数据,但如果两次调用之间不考虑Session问题将无法通过服务器的验证。通过使用HttpWatch工具观察三次点击过程中提交到服务器的http头以及服务器返回的Res发现其中有一个"Set-Cookie"的属性,其值形式为:"JSESSIONID=XXXXXX",于是通过WebClient.ResponseHeaders["Set-Cookie"]属性获得SessionID,并附加到下一次链接提交的HttpHead中实现了在WebClient的两次提交中保持Session。
    代码如下:
 1WebClient webClient = new WebClient();
 2string srcString = webClient.DownloadString(tarurl1);
 3string header = webClient.ResponseHeaders["Set-Cookie"];
 4webClient.Headers.Add("Content-Type""text/html");
 5webClient.Headers.Add("Cookie",header);//在给服务器发送消息时加上这个Session值
 6webClient.Headers.Add("Referer", tarurl1);
 7srcString = webClient.DownloadString(tarurl2);
 8int index = srcString.IndexOf(tar);
 9string synid = srcString.Substring(index + tar.Length, 13);
10tarurl3 += synid;
11string tmp = srcString.Substring(index + tar.Length, srcString.Length-index-tar.Length);
12int itmp = tmp.IndexOf("点击率:");
13int toll = GetToll(tmp.Substring(itmp, 100)) + 1;
14statusStrip1.Items[0].Text = "票数:" + toll;
15webClient.Headers.Add("Content-Type""text/html");
16webClient.Headers.Add("Cookie", header);//在给服务器发送消息时加上这个Session值
17webClient.Headers.Add("Referer", tarurl2);
18srcString = webClient.DownloadString(tarurl3);
    其中第2行为获取第一次点击内容,第3行是获得SessionID,第5行就是附加SessionID到第二次链接;8、9、10是获得随机数,11、12、13获得票数;15、16、17、18是完成投票。其中6、17只是添加一个引用头,不知道是否是必须的。
    需要说明的是,此方法对于有验证码的登录方式是无效的。而且第一次链接是一个DownloadString方法来实现类似登录的功能,之所以不是POST,是因为服务器并没有对此要求太严格,否则要用到UpdateData方法了。
posted @ 2007-12-14 19:38  badwood  阅读(3602)  评论(2编辑  收藏  举报
Badwood's Blog