如何在google analytics api调用中解决403错误

时间:2011-12-06 17:50:51

标签: c# google-analytics http-status-code-403

我正在使用以下帖子中的代码: Google Analytics API - Programmatically fetch page views in server side

但是在下方突出显示的行中收到403禁止错误。我不认为这是凭据问题,因为我的凭据是正确的,因为我已经检查并仔细检查过,并且我还使用这些凭据登录到分析帐户。那么也许它是一些文件夹权限问题?

//-------------- 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();
}

1 个答案:

答案 0 :(得分:0)

如果您过于频繁地致电Google AnalyticsAPI,请you could get 403 Forbidden errors。从那个链接:

  

General Analytics API配额。这些适用于Analytics API,即Management API和Core Reporting API:
   - 每个项目每天50,000个请求    - 每个IP每秒10次查询(QPS)

当我的应用程序连续拨打太多电话时,我看到了从AdWords API返回的403错误,因此可能是导致问题的原因。

修改

如果您根本无法拨打任何电话,请查看“开始之前”中列出的here步骤。根据文档,您需要先通过Google API控制台注册您的应用程序,然后才能使用该API。