用C# Console程序访问Web站点时,如何设置Session信息?

JadyWang 2006-06-29 03:33:52
在IE中输入一个认证URL,比如:https://login.WebSite.com.tr/authenticate4outprg.aspx?userid=eZhang&password=XXXYYY。
然后在同一个IE窗口中输入https://fosn.WebSite.com.tr/prg_daily_summary_xml.asp?e=1来下载文件。

我用下面代码试图完成上述动作:
string url1 = "https://login.WebSite.com.tr/authenticate4outprg.aspx?userid=eZhang&password=XXXYYY";
string url2 = "https://fosn.WebSite.com.tr/prg_daily_summary_xml.asp?e=1";

//Log In
HttpWebRequest req1 = (HttpWebRequest)WebRequest.Create(url1);
req1.Method = "POST";
req1.ContentType = "application/x-www-form-urlencoded";
req1.ContentLength = 0;

HttpWebResponse res = (HttpWebResponse)req1.GetResponse();
StreamReader sr1 = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr1 = sr1.ReadToEnd();
Console.WriteLine(backstr1);
sr1.Close();
res.Close();



//Down Load ASN File
WebClient wc = new WebClient();
wc.DownloadFile(url2,"C:\\haha.xml");
res.Close();


但是,上面代码的两次请求不是同一个Session,认证信息带不到下载页面,故无法下载。哪位知道如何把session信息带到下一个request?
...全文
464 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
Knight94 2006-06-29
  • 打赏
  • 举报
回复
look up file info using "HttpWebResponse.Headers" property
JadyWang 2006-06-29
  • 打赏
  • 举报
回复
不过还是有问题,我发现按照上面代码,只能取到下载文件的内容,不能取到文件名,我只能在写入本地的时候自己起个名字。各位继续赐教……谢谢
JadyWang 2006-06-29
  • 打赏
  • 举报
回复
上面问题解决。我使用了httpwebrequest来代替webclient实现下载,并将两次的HttpWebRequest的CookieContainer串了起来:
string url1 = "https://login.WebSite.com.tr/authenticate4outprg.aspx?userid=eZhang&password=XXXYYY";
string url2 = "https://fosn.WebSite.com.tr/prg_daily_summary_xml.asp?e=1";

CookieContainer cc = new CookieContainer();
//Log In
HttpWebRequest req1 = (HttpWebRequest)WebRequest.Create(url1);
req1.CookieContainer = cc;
req1.Method = "POST";
req1.ContentType = "application/x-www-form-urlencoded";
req1.ContentLength = 0;

HttpWebResponse res = (HttpWebResponse)req1.GetResponse();
StreamReader sr1 = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr1 = sr1.ReadToEnd();
Console.WriteLine(backstr1);
sr1.Close();
res.Close();

//Download File
HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(url2);
req2.CookieContainer = cc;
req2.Method = "POST";
req2.ContentType = "application/x-www-form-urlencoded";
req2.ContentLength = 0;

HttpWebResponse res = (HttpWebResponse)req2.GetResponse();
StreamReader sr2 = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr2 = sr2.ReadToEnd();

//将backstr2的内容写入本地文件
……………………………………
Knight94 2006-06-29
  • 打赏
  • 举报
回复
Have a try!

//Down Load ASN File
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.DownloadFile(url2,"C:\\haha.xml");
res.Close();

110,532

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧