我在数据库中有一些网址。问题是网址是重定向到我想要的网址。
我有类似的东西
http://www.mytestsite.com/test/test/?myphoto=true
现在,如果我去这个网站,它会重定向到照片,所以网址最终会被
http://www.mytestsite.com/test/myphoto.jpg
是否有可能以某种方式通过C#抓取(下载)然后让它重定向并获取真正的网址以便我可以下载图像?
答案 0 :(得分:7)
我认为你是在HttpWebRequest.AllowAutoRedirect财产之后。该属性获取或设置一个值,该值指示请求是否应遵循重定向响应。
取自MSDN的示例
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.MaximumAutomaticRedirections=1;
myHttpWebRequest.AllowAutoRedirect=true;
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
答案 1 :(得分:0)
在将HttpWebRequest
与SharePoint外部URL结合使用时总是遇到完全重定向的问题;我根本无法正常工作。
经过一番忙碌之后,我发现{strong> 也可以用WebClient
完成,这对我来说更可靠。
要使其与WebClient
一起使用,您似乎必须创建一个从WebClient
派生的类,以便您可以手动将AllowAutoRedirect
强制为true。
我在这个in this answer上写了一些东西,它借用了代码from this question。
关键代码是:
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; } }