使用HttpWebRequest下载经过重定向的文件
使用 req.AllowAutoRedirect = true; 可以直接下载到文件,但不能得到文件名,通过使用req.AllowAutoRedirect = false;得到响应的Location,从而可以得到所请求的真实地址,也就可以得到文件名了。下面的代码可以进行下载到真实的文件名。需要注意的是,后面的req.AllowAutoRedirect = true;必须设置为 true,如果设置为false,则不能下载到完整的文件。
C# 代码
string Cookie = String.Empty;
String url = "http://search.patentstar.com.cn/cprs2010/Docdb/GetBns.aspx?PNo=APP201180002436";
String refer = url.Substring(0, url.LastIndexOf("/") + 1);
System.Net.HttpWebRequest req = System.Net.HttpWebRequest.Create(url) as System.Net.HttpWebRequest;
req.AllowAutoRedirect = false;
req.Referer = refer;
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
System.Net.HttpWebResponse res = req.GetResponse() as System.Net.HttpWebResponse;
System.Net.WebHeaderCollection headers = res.Headers;
String newUrl = "";
if ((res.StatusCode == System.Net.HttpStatusCode.Found) ||
(res.StatusCode == System.Net.HttpStatusCode.Redirect) ||
(res.StatusCode == System.Net.HttpStatusCode.Moved) ||
(res.StatusCode == System.Net.HttpStatusCode.MovedPermanently))
{
newUrl = headers["Location"];
newUrl = newUrl.Trim();
}
if (headers["Set-Cookie"] != null)
{
Cookie = headers["Set-Cookie"];
}
NameValueCollection collHeader = new NameValueCollection();
if (Cookie.Length > 0)
{
collHeader.Add("Cookie", Cookie);
}
res.Close();
req = null;
String fileName = newUrl.Substring(newUrl.LastIndexOf("/") + 1);
req = System.Net.HttpWebRequest.Create(newUrl) as System.Net.HttpWebRequest;
req.AllowAutoRedirect = true;
req.Referer = url;
req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
res = req.GetResponse() as System.Net.HttpWebResponse;
System.IO.Stream stream = res.GetResponseStream();
byte[] buffer = new byte[32 * 1024];
int bytesProcessed = 0;
System.IO.FileStream fs = System.IO.File.Create(Server.MapPath(fileName));
int bytesRead;
do
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, bytesRead);
bytesProcessed += bytesRead;
}
while (bytesRead > 0);
fs.Flush();
fs.Close();
res.Close();
Response.Write("文件 " + fileName + " 已经下载完成。");
作者 孟宪会
相关新闻>>
- 发表评论
-
- 最新评论 更多>>