首页 > 解决方案 > 如何在 C# 中以压缩格式下载 Google Drive 文件

问题描述

我正在尝试通过下载压缩格式的谷歌驱动器文件来提高我的应用程序的性能。我以此为参考。

https://developers.google.com/drive/api/v2/performance#gzip

我在发送的 HttpwebRequest 的标头中尝试了各种方法,但未能成功。任何人都可以在这方面帮助我。这是我正在使用的代码。

    public void DownloadFile(string url, string filename)
    {
        try
        {
            var tstart = DateTime.Now;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            request.Timeout = 60 * 1000; // Timeout
            request.Headers.Add("Authorization", "Bearer" + " " + AuthenticationKey);                
            request.Headers.Add("Accept-Encoding", "gzip,deflate");
            request.UserAgent = "MyApplication/11.14 (gzip)";                

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            string content = response.GetResponseHeader("content-disposition");
            Console.WriteLine(content);

            System.IO.Stream received = response.GetResponseStream();
            using (System.IO.FileStream file = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
            {
                received.CopyTo(file);
            }

            var tend = DateTime.Now;
            Console.WriteLine("time taken to download '{0}' is {1} seconds", filename, (tend - tstart).TotalSeconds);
        }
        catch (WebException e)
        {
            Console.WriteLine("Exception thrown - {0}", e.Message);
        }
    }

标签: c#google-drive-apiuser-agentsystem.net.httpwebrequesthttp-accept-encoding

解决方案


使用gzip

减少每个请求所需带宽的一种简单方便的方法是启用 gzip 压缩。尽管这需要额外的 CPU 时间来解压缩结果,但与网络成本的权衡通常非常值得。

为了接收 gzip 编码的响应,您必须做两件事:设置 Accept-Encoding 标头,并修改您的用户代理以包含字符串 gzip。以下是启用 gzip 压缩的正确格式的 HTTP 标头示例:

Accept-Encoding: gzip
User-Agent: my program (gzip)

Gzip 压缩来自 API 的实际响应。不是您正在下载的实际文件。例如file.export返回一个file.resource json 对象,该对象将被压缩。不是您需要下载的文件的实际数据。文件以相应的类型下载管理下载 虽然谷歌可能能够在您下载时将 google doc 文件转换为 ms word 文件。它不会将 google doc 文件转换为 zip 文件,以便您可以下载压缩文件。


推荐阅读