如何使用HttpWebRequest和HttpWebResponse类(Cookies,凭据等)下载文件

谢谢icktoofay,我尝试使用HttpWebRequestHttpWebResponse

当我通过传递诸如UserName和Password之类的凭证来请求URL时。

我将在响应中返回会话ID。

获得该会话ID后,如何进一步移动。

使用凭据/ cookie跟踪经过身份validation的用户。 我正在下载文件的确切url和凭据。 如果你想使用Cookies,我会。 我需要读取文件数据并将其写入/保存在指定位置。

我正在使用的代码是;

 string username = ""; string password = ""; string reqString = "http://sofzh.miximages.com/c%23/uf.Length; int bytesRead = 0; while (bytesToRead  0) { int n = str.Read(inBuf, bytesRead,bytesToRead); if (n==0) break; bytesRead += n; bytesToRead -= n; } FileStream fstr = new FileStream(weather.jpg", FileMode.OpenOrCreate, FileAccess.Write); fstr.Write(inBuf, 0, bytesRead); str.Close(); fstr.Close(); 

我是这样做的:

 const string baseurl = "http://www.some......thing.com/"; CookieContainer cookie; 

第一种方法登录到Web服务器并获取会话ID:

 public Method1(string user, string password) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(baseurl); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string login = string.Format("go=&Fuser={0}&Fpass={1}", user, password); byte[] postbuf = Encoding.ASCII.GetBytes(login); req.ContentLength = postbuf.Length; Stream rs = req.GetRequestStream(); rs.Write(postbuf,0,postbuf.Length); rs.Close(); cookie = req.CookieContainer = new CookieContainer(); WebResponse resp = req.GetResponse(); resp.Close(); } 

另一种方法从服务器获取文件:

 string GetPage(string path) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(path); req.CookieContainer = cookie; WebResponse resp = req.GetResponse(); string t = new StreamReader(resp.GetResponseStream(), Encoding.Default).ReadToEnd(); return IsoToWin1250(t); } 

请注意,我将页面作为字符串返回。 您可能最好将其作为bytes []保存到磁盘。 如果你的jpeg文件很小(它们通常不是千兆字节),你可以简单地将它们放到内存流中,然后保存到磁盘。 在C#中需要大约2或3条简单的行,而不是像上面提供的那样,有30行强硬的代码存在潜在的危险内存泄漏。