WebClient未从提供的网址

时间:2016-01-26 03:14:42

标签: c# webclient webclient-download web-client

我想从Linux发行版下载.torrent文件,但由于某种原因,从我的应用程序下载的最终文件与手动下载的文件不同。我的应用程序下载的那个有31KB而且是一个无效的.torrent文件,而正确的一个(当我手动下载时)有41KB并且它是有效的。

我要下载的文件的网址是http://torcache.net/torrent/C348CBCA08288AE07A97DD641C5D09EE25299FAC.torrent

为什么会发生这种情况?如何下载相同的文件(有效文件,41KB)?

感谢。

下载上述文件的方法中的C#代码:

        string sLinkTorCache = @"http://torcache.net/torrent/C348CBCA08288AE07A97DD641C5D09EE25299FAC.torrent";
        using (System.Net.WebClient wc = new System.Net.WebClient())
        {
            var path = @"D:\Baixar automaticamente"; // HACK Pegar isso dos settings na versão final
            var data = Helper.Retry(() => wc.DownloadData(sLinkTorCache), TimeSpan.FromSeconds(3), 5);
            string fileName = null;

            // Try to extract the filename from the Content-Disposition header
            if (!string.IsNullOrEmpty(wc.ResponseHeaders["Content-Disposition"]))
            {
                fileName = wc.ResponseHeaders["Content-Disposition"].Substring(wc.ResponseHeaders["Content-Disposition"].IndexOf("filename=") + 10).Replace("\"", "");
            }

            var torrentPath = Path.Combine(path, fileName ?? "Arch Linux Distro");

            if (File.Exists(torrentPath))
            {
                File.Delete(torrentPath);
            }

            Helper.Retry(() => wc.DownloadFile(new Uri(sLinkTorCache), torrentPath), TimeSpan.FromSeconds(3), 5);
        }

Helper.Retry(尝试在HTTP异常情况下再次执行该方法):

    public static void Retry(Action action, TimeSpan retryInterval, int retryCount = 3)
    {
        Retry<object>(() =>
        {
            action();
            return null;
        }, retryInterval, retryCount);
    }

    public static T Retry<T>(Func<T> action, TimeSpan retryInterval, int retryCount = 3)
    {
        var exceptions = new List<Exception>();

        for (int retry = 0; retry < retryCount; retry++)
        {
            try
            {
                if (retry > 0)
                    System.Threading.Thread.Sleep(retryInterval); // TODO adicionar o Using pro thread
                return action();
            }
            catch (Exception ex)
            {
                exceptions.Add(ex);
            }
        }

        throw new AggregateException(exceptions);
    }

1 个答案:

答案 0 :(得分:1)

我最初虽然该网站正在响应垃圾,但如果它认为这是来自机器人的请求(也就是说,它正在检查一些标题)。看了Fiddler后,对于Web浏览器和代码,返回的数据似乎完全相同。这意味着,我们没有正确缩小(提取)响应。 Web服务器压缩数据非常常见(使用像gzip这样的东西)。 WebClient 会自动缩小数据。

使用Automatically decompress gzip response via WebClient.DownloadData的答案 - 我设法让它正常工作。

另请注意,您要下载文件两次。你不需要这样做。

工作代码:

//Taken from above linked question
class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}

使用它:

string sLinkTorCache = @"http://torcache.net/torrent/C348CBCA08288AE07A97DD641C5D09EE25299FAC.torrent";
using (var wc = new MyWebClient())
{
  var path = @"C:\Junk";
  var data = Helper.Retry(() => wc.DownloadData(sLinkTorCache), TimeSpan.FromSeconds(3), 5);
  string fileName = "";

  var torrentPath = Path.Combine(path, fileName ?? "Arch Linux Distro.torrent");

  if (File.Exists(torrentPath))
      File.Delete(torrentPath);

    File.WriteAllBytes(torrentPath, data);
}