【问题标题】:Download file through code that has a redirect?通过具有重定向的代码下载文件?
【发布时间】:2012-07-31 22:03:30
【问题描述】:

我在数据库中有一些网址。问题是网址是重定向到我想要的网址。

我有这样的事情

http://www.mytestsite.com/test/test/?myphoto=true

现在如果我去这个网站,它会重定向到照片,所以网址最终会是

http://www.mytestsite.com/test/myphoto.jpg

是否可以通过 C# 以某种方式抓取(下载)然后让它重定向并获取真实的 url,以便我可以下载图像?

【问题讨论】:

  • 所有这些链接都被破坏并没有帮助。您知道,您可以使用 php 来提供图像。如果您通过 HTML 重定向完成此操作,则必须解析 HTML 并搜索重定向标记。通过 javascript 来做这件事会很痛苦。
  • @Wug - 谁说过关于 php 或 javascript 的事?他没有提供任何服务,他想下载通过重定向从服务器访问的图像。看起来他不会控制服务器。
  • 不,我不控制服务器。我需要将数百个 img 移动到新服务器,所以我需要下载它们,但我拥有的一些链接是链接,其唯一目的是转到 pg 并重定向到实际的 img(不知道他们为什么这样做,而不仅仅是有直接链接到img)。我无法提供有效链接(而且我不知道有任何公共网站这样做),因为这是公司财产。

标签: c# .net


【解决方案1】:

我想你在HttpWebRequest.AllowAutoRedirect 属性之后。该属性获取或设置一个值,该值指示请求是否应遵循重定向响应。

来自 MSDN 的示例

HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");    
myHttpWebRequest.MaximumAutomaticRedirections=1;
myHttpWebRequest.AllowAutoRedirect=true;
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

【讨论】:

  • 正是我想要的!没想到httpWebRequest只是在看Webclient(我常用的)。
  • 我认为还应该提到你必须关闭myHttpWebResponse。如果您尝试在 WebClient 给您很多超时之后立即使用它。
  • @chobo2 是的,你的权利,MSDN 应该提到这是必要/良好的做法
【解决方案2】:

在将 HttpWebRequest 与 SharePoint 外部 URL 一起使用时,我在尝试让 HttpWebRequest 始终完全重定向时遇到问题;我根本无法让它工作。

经过一番折腾后,我发现这也可以WebClient 来完成,这对我来说更可靠。

要使其与WebClient 一起使用,您似乎必须创建一个派生自WebClient 的类,以便您可以手动强制AllowAutoRedirect 为真。

我在这个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;
  }
}

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 2021-09-17
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多