c# - 如何使用 C# 下载 Google SpreadSheets?

标签 c# google-sheets google-data-api

我可以使用我从网上找到的以下代码使用我的应用程序登录到谷歌。它返回一个授权码作为响应。谷歌帮助说这个授权码应该用于发送 future 的 POST/GET 请求。

我需要从以下网站下载 Excel 格式的电子表格 http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=DOCUMENT_ID&fmcmd=4当我登录到 google 时,我通常可以通过浏览器执行此操作。

如何使用 C# 中的授权代码发送对上述文件的请求? 我在 SO 中看到了一个使用 Google Data API 的线程。我不想利用它。

下面是登录的代码示例。它工作正常。

        string str = "/accounts/ClientLogin HTTP/1.0 Content-type: application/x-www-form-urlencoded accountType=GOOGLE&Email=myname@gmail.com&Passwd=password&service=cl&source=Gulp-CalGulp-1.05";

        string uri = "https://www.google.com/accounts/ClientLogin";

        HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri); 
        request.KeepAlive = false;
        request.ProtocolVersion = HttpVersion.Version10;
        request.Method = "POST";

        byte[] postBytes = Encoding.ASCII.GetBytes(str);

        request.ContentType = "application/x-www-form-urlencoded";
        request.ContentLength = postBytes.Length;
        Stream requestStream = request.GetRequestStream();


        requestStream.Write(postBytes, 0, postBytes.Length);
        requestStream.Close();


        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StringBuilder sb = new StringBuilder();

        string webresponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
        int AuthIndex = webresponse.IndexOf("Auth=");

        sb.Append(webresponse);
        sb.Append("\n");
        sb.Append(response.StatusCode);

        richTextBox1.Text = sb.ToString();
        string authCode = webresponse.Substring(AuthIndex + 5, webresponse.Length - (AuthIndex + 5));

编辑: 这是我根据 miffTheFox 的回复得到的回复:

<html><head><title>Redirecting</title>
<meta http-equiv="refresh" content="0; url=&#39;http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=p_zC6U3bOsLTuXeUdmQI1RA&amp;fmcmd=4&amp;pli=1&amp;auth=DQAAAIoAAAAfbQUnX8EaZzQcBSIRJSeU4xtFF6ITt9069JLJyJsoqFGMzSE8HrvArHmGPoA-Wf2CbhnDQv_bGKXye2_qyL6EAhTEdOs6Alz-VMeYFsqdGlYjxospBokgCO1958kSVuVFRe9UuKkfV2f_6ZX8SROMkMNdMz3MW8Wh3UNmflIX4E92CpnMleSjCRVpH9x5gSQ&amp;gausr=username%40gmail.com&#39;"></head>
<body bgcolor="#ffffff" text="#000000" link="#0000cc" vlink="#551a8b" alink="#ff0000"><script type="text/javascript" language="javascript">
    location.replace("http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key\x3dp_zC6U3bOsLTuXeUdmQI1RA\x26fmcmd\x3d4\x26pli\x3d1\x26auth\x3dDQAAAIoAAAAfbQUnX8EaZzQcBSIRJSeU4xtFF6ITt9069JLJyJsoqFGMzSE8HrvArHmGPoA-Wf2CbhnDQv_bGKXye2_qyL6EAhTEdOs6Alz-VMeYFsqdGlYjxospBokgCO1958kSVuVFRe9UuKkfV2f_6ZX8SROMkMNdMz3MW8Wh3UNmflIX4E92CpnMleSjCRVpH9x5gSQ\x26gausr\x3dusername%40gmail.com")
  </script></body></html>

如果我将流保存为 HTML 并在浏览器中打开它,它会提示我需要直接下载 Excel 文件。

最佳答案

我实际上做过一个项目,以前做过类似的事情,只是它使用了 Google Reader,尽管我假设 Google 授权过程是相同的。

首先,对于登录响应中的每个键/值对,您必须将其转换为 cookie。

string loginResponseText = new StreamReader(loginResponse.GetResponseStream()).ReadToEnd();
CookieContainer cookies = new CookieContainer();
foreach (string ln in loginResponseText.Split('\n'))
{
    if (!ln.Contains("=")) continue;
    string tId = ln.Substring(0, ln.IndexOf('=')).Trim();
    string tVal = ln.Substring(ln.IndexOf('=') + 1).Trim();
    cookies.Add(new Cookie(tId, tVal, "/", "www.google.com"));
}

然后,您必须为您发出的请求设置 cookie 容器。

string url = string.Format("http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key={0}&fmcmd=4", documentID);
HttpWebRequest rqForFile = (HttpWebRequest)WebRequest.Create(url);
rqForFile.CookieContainer = cookies;
WebResponse respForFile = rUnread.GetResponse();

尽情享受吧!

编辑:如何解码返回的 HTML!

您需要使用正则表达式来解析 URL,然后使用一种方法对其进行 HTML 解码。 对我们来说幸运的是,Microsoft 在 System.Web 中提供了一个。只需将对它的引用添加到您的项目中即可。

确保将 using System.Text.RegularExpressions 添加到文件顶部!

Match m = Regex.Match("content=\"0; url=&#39;(.+)&#39;");
if (!m.Success) throw new Exception(); // Or some other method of making sure the result is okay.
string finalurl = m.Groups[1].ToString();
finalurl = System.Web.HttpUtility.HtmlDecode(finalurl);

然后只需使用您的 CookieContianer 获取最终网址! (这未经测试,但应该有效!)

关于c# - 如何使用 C# 下载 Google SpreadSheets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/943995/

相关文章:

php - 以编程方式登录 Google 数据 API

C# 检查第二个屏幕的方向

c# - 如何让程序运行直到按下转义键?

charts - 谷歌电子表格图表中的命名范围?

用于通过特定字符分隔条目的正则表达式

java - 如何在 android 中解析 Google 公共(public)日历?

C# 如何在列表框中用图标显示进程

c# - .NET 程序员的 JavaScript 编辑器

java - 在 Android 上使用 Google 登录访问 Google 电子表格(或其他 Google 应用程序)

java - Google Documents List Api - 没有 feed.getNextLink() 的分页结果