使用HttpWebRequest下载文件

时间:2012-11-07 17:55:12

标签: asp.net httpwebrequest

如何使用HttpWebRequest下载pdf文件? 我想下载pdf文件并将其保存到我的系统 我无法使用WebClient下载,因为我需要为我的请求添加cookie

<code>
    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
    HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(Url);
    CookieContainer cookieJar = new CookieContainer();
    cookieJar.Add(new Cookie("cookieName", "value", "/", "domain));      
    (Request as HttpWebRequest).CookieContainer = cookieJar;
     HttpWebResponse Response = (HttpWebResponse)Request.GetResponse();


</code>

2 个答案:

答案 0 :(得分:0)

使用HttpWebRequest GetResponseStream()将响应正文作为流获取,然后将其保存到文件中。

答案 1 :(得分:0)

尝试这样的事情: -

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);
}