我已经可以登录到已重定向网页(我保存的cookies),此代码
CookieCollection cookies = new CookieCollection();
HttpWebRequest cookieRequest = (HttpWebRequest)WebRequest.Create("https://www.loginpage.com/");
cookieRequest.CookieContainer = new CookieContainer();
cookieRequest.CookieContainer.Add(cookies);
HttpWebResponse cookieResponse = (HttpWebResponse)cookieRequest.GetResponse();
cookies = cookieResponse.Cookies;
string postData = "name=********&password=*********&submit=submit";
HttpWebRequest loginRequest = (HttpWebRequest)WebRequest.Create("https://www.loginpage.com/");
loginRequest.CookieContainer = new CookieContainer();
loginRequest.CookieContainer.Add(cookies);
loginRequest.Method = WebRequestMethods.Http.Post;
loginRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
loginRequest.AllowWriteStreamBuffering = true;
loginRequest.ProtocolVersion = HttpVersion.Version11;
loginRequest.AllowAutoRedirect = true;
loginRequest.ContentType = "application/x-www-form-urlencoded";
byte[] byteArray = Encoding.ASCII.GetBytes(postData);
loginRequest.ContentLength = byteArray.Length;
Stream newStream = loginRequest.GetRequestStream(); //open connection
newStream.Write(byteArray, 0, byteArray.Length); // Send the data.
newStream.Close();
这工作得很好,但我需要从那里下载.xls文件,它位于此处(例如)
https://www.loginpage.com/export_excel.php?export_type=list
为了这个,我试过这个代码
HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create("https://www.loginpage.com/export_excel.php?export_type=list");
HttpWebResponse ws = (HttpWebResponse)wr.GetResponse();
Stream str = ws.GetResponseStream();
byte[] inBuf = new byte[100000];
int bytesReadTotal = 0;
string path = @"d:\test.xlsx";
FileStream fstr = new FileStream(path, FileMode.Create, FileAccess.Write);
while (true)
{
int n = str.Read(inBuf, 0, 100000);
if ((n == 0) || (n == -1))
{
break;
}
fstr.Write(inBuf, 0, n);
bytesReadTotal += n;
}
str.Close();
fstr.Close();
但它不工作,现在我坚持这
string dLink = "https://www.loginpage.com/export_excel.php?export_type=list";
HttpWebRequest fileRequest = (HttpWebRequest)HttpWebRequest.Create(dLink);
fileRequest.CookieContainer = new CookieContainer();
fileRequest.CookieContainer.Add(cookies);
fileRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
HttpWebResponse fileResponse = (HttpWebResponse)fileRequest.GetResponse();
for (int i = 0; i < fileResponse.Headers.Count; ++i)
richTextBox1.Text += "\nHeader Name: " + fileResponse.Headers.Keys[i] + ", Value :" + fileResponse.Headers[i];
当然,没有下载文件。 我试图让头现在才明白什么我从网络上获得? 我已经从FIL esharing像rghost或filehippo页面下载了我的脚本一些文件,但这个是行不通的。