Use req. allowAutoRedirect = true; the file can be downloaded directly, but the file name cannot be obtained. You can use req. allowAutoRedirect = false; get the Location of the response, so that you can get the actual address of the request and get the file name. The following code downloads a real file name. Note that req. AllowAutoRedirect = true must be set to true. If it is set to false, it cannot be downloaded to the complete file.
C # code
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 ("file" + fileName + "has been downloaded. ");
Author: Meng xianhui