我可以使用我从网上找到的以下代码使用我的应用程序登录谷歌。它返回一个授权码作为响应。谷歌帮助说这个验证码应该被用来发送未来的 POST/GET 请求。
我需要从http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=DOCUMENT_ID&fmcmd=4下载 Excel 格式的电子表格, 当我登录到谷歌时,我通常可以从浏览器中执行此操作。
如何使用 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='http://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=p_zC6U3bOsLTuXeUdmQI1RA&fmcmd=4&pli=1&auth=DQAAAIoAAAAfbQUnX8EaZzQcBSIRJSeU4xtFF6ITt9069JLJyJsoqFGMzSE8HrvArHmGPoA-Wf2CbhnDQv_bGKXye2_qyL6EAhTEdOs6Alz-VMeYFsqdGlYjxospBokgCO1958kSVuVFRe9UuKkfV2f_6ZX8SROMkMNdMz3MW8Wh3UNmflIX4E92CpnMleSjCRVpH9x5gSQ&gausr=username%40gmail.com'"></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 文件。