通过具有重定向的代码下载文件?
我在数据库中有一些url。 问题是url是重定向到我想要的url。
我有类似的东西
http://www.mytestsite.com/test/test/?myphoto=true
现在,如果我去这个网站,它会重定向到照片,所以url将最终成为
http://www.mytestsite.com/test/myphoto.jpg
有可能通过C#以某种方式刮(下载)然后重定向并获取真正的URL,以便我可以下载图像吗?
我想你是在HttpWebRequest.AllowAutoRedirect属性之后。 该属性获取或设置一个值,该值指示请求是否应遵循重定向响应。
从MSDN获取的示例
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com"); myHttpWebRequest.MaximumAutomaticRedirections=1; myHttpWebRequest.AllowAutoRedirect=true; HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
我在尝试让HttpWebRequest
在与SharePoint外部URL一起使用时始终完全重定向时遇到了问题; 我根本无法让它发挥作用。
经过大量的讨论,我发现这也可以通过WebClient
完成,这对我来说更可靠。
要使其与WebClient
您似乎必须创建一个派生自WebClient
的类,以便您可以手动强制AllowAutoRedirect
为true。
我在这个答案中写了更多关于此的内容,其中借用了这个问题的代码。
关键代码是:
class CustomWebclient: WebClient { [System.Security.SecuritySafeCritical] public CustomWebclient(): base() { } public CookieContainer cookieContainer = new CookieContainer(); protected override WebRequest GetWebRequest(Uri myAddress) { WebRequest request = base.GetWebRequest(myAddress); if (request is HttpWebRequest) { (request as HttpWebRequest).CookieContainer = cookieContainer; (request as HttpWebRequest).AllowAutoRedirect = true; } return request; } }