如何解决403错误在谷歌分析API调用
本文关键字:谷歌 调用 API 错误 何解决 解决 | 更新日期: 2023-09-27 18:16:53
我在下面的帖子中使用代码:Google Analytics API -在服务器端以编程方式获取页面浏览量
但是在下面高亮显示的行上得到一个403 forbidden错误。我不认为这是一个凭证问题,因为我的凭证是正确的,因为我已经检查和再次检查了,并且我用这些凭证登录了分析帐户。所以可能是文件夹权限问题?
//-------------- Get Auth Token -------------------
WebClient webClient = new WebClient();
NameValueCollection data = new NameValueCollection();
data.Add("accountType", "GOOGLE");
data.Add("Email", "xxxx@gmail.com");
data.Add("Passwd", "xxxx");//Passwd, not a misspell.
data.Add("service", "analytics");
data.Add("source", "xxxx-xxxx-xx");//Could be anything.
byte[] bytes = webClient.UploadValues("https://www.google.com/accounts/ClientLogin", "POST", data);
string tokens = Encoding.UTF8.GetString(bytes);
string authToken = extractAuthToken(tokens);
//-------------- Get page views -------------------
string feed = "https://www.google.com/analytics/feeds/data";
//Required:
string ids = "ga:xxxx";
string metrics = "ga:pageviews";
string startDate = "2011-06-25";
string endDate = "2011-07-25";
//Optional:
string dimensions = "ga:pagePath";
string sort = "-ga:pageviews";
string feedUrl = string.Format("{0}?ids={1}&dimensions={2}&metrics={3}&sort={4}&start-date={5}&end-date={6}",
feed, ids, dimensions, metrics, sort, startDate, endDate);
webClient.Headers.Add("Authorization", "GoogleLogin " + authToken);
// This is the line I get the 403 error on:
**string result = webClient.DownloadString(feedUrl);**
//-------------- Extract data from xml -------------------
XDocument xml = XDocument.Parse(result);
var ns1 = "{http://www.w3.org/2005/Atom}";
var ns2 = "{http://schemas.google.com/analytics/2009}";
var q = from entry in xml.Descendants()
where entry.Name == ns1 + "entry"
select new
{
PagePath = entry.Element(ns2 + "dimension").Attribute("value").Value,
Views = entry.Element(ns2 + "metric").Attribute("value").Value
};
//-------------- Do something with data -------------------
foreach (var page in q)
{
Debug.WriteLine(page.PagePath + " " + page.Views);
}
//-------------- Help Method -------------------
private string extractAuthToken(string data)
{
var tokens = data.Split(new string[] { "'n" }, StringSplitOptions.RemoveEmptyEntries);
return tokens.Where(token => token.StartsWith("Auth=")).Single();
}
如果你过于频繁地调用Google Analytics API,你可能会得到403个Forbidden error。从该链接:
通用分析API配额。这些都适用于分析API,即管理API和核心报告API:
-每个项目每天有50,000个请求
-每个IP每秒10次查询
当我的应用程序连续调用太多时,我看到AdWords API返回了403个错误,所以这可能是你的问题的原因。
编辑
如果你根本无法拨打任何电话,那么请查看"开始之前"下面列出的步骤。根据文档,在使用API之前,您需要通过Google API控制台注册您的应用程序。