c# - 如何在 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);
}
}
解决方案
使用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 文件,以便您可以下载压缩文件。
推荐阅读
- json - 如何使用 ARM 模板同时创建多个警报
- adapter - 有什么方法可以解析位图被屏蔽或没有任何位图的 ISO8583 消息?
- swift - 如何保证任何 DispatchQueue(或 OperationQueue)仅在异步任务的非主线程中运行?
- laravel - 如何以雄辩的方式将第二张和第三张桌子连接在一起
- android - RecyclerView 图像显示工件
- javascript - 选择/选中 td 类中的第一个复选框?
- python - 为什么 HoughCircles 没有检测到一个圆圈?minDist 是如何工作的?
- mysql - 在sql查询中使用Max(date)聚合函数时,返回所有列中包含Null值的行
- java - 未检测到同时碰撞
- sql - Oracle SQL - 从给定列表中选择不同的值