我正在尝试编写一个在线应用程序来使用谷歌服务帐户访问我的谷歌分析数据。这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GA_server2server_POC.Models
{
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Util;
using Google.Apis.Services;
using Google.Apis.Requests;
public class Oauth_With_API
{
public static void ApiTest()
{
log4net.Config.XmlConfigurator.Configure();
const string ServiceAccountId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
const string ServiceAccountUser = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdeveloper.gserviceaccount.com";
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2("C:\\Users\\rcarter\\Downloads\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = "https://www.googleapis.com/auth/analytics.readonly",
ServiceAccountId = ServiceAccountUser
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = authenticator
});
string profileId = "ga:xxxxxxxx";
string startDate = "2013-07-01";
string endDate = "2013-07-15";
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
GaData data = request.Execute(); //error occurs here. After this, thread exits.
Console.WriteLine(data.TotalResults);
}
}
}
到目前为止我的代码执行,但我得到以下输出:
WebDev.WebServer40.exe Information: 0 : DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official)
WebDev.WebServer40.exe Information: 0 : Preparing to send AssertionFlowMessage (2.0) message.
WebDev.WebServer40.exe Information: 0 : Sending AssertionFlowMessage request.
WebDev.WebServer40.exe Information: 0 : HTTP POST https://accounts.google.com/o/oauth2/token
WebDev.WebServer40.exe Information: 0 : The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse message: {error,
}
WebDev.WebServer40.exe Information: 0 : Received UnauthorizedResponse response.
此后,线程退出,程序拒绝打印任何数据。麻烦似乎发生在request.Execute();
。我发现特别令人困惑的部分是,如果我在 上放置断点Console.WriteLine(data.TotalResults);
,我可以在局部变量中看到我想要的数据data
。它包含我想要打印的所有内容,但我无法确定错误的原因,使其无法在request.Execute();
. 经过大量搜索,我对上面列出的错误完全没有发现。
我正在使用的代码是基于这里给出的这个问题的答案。自从该问题得到解答以来,谷歌分析库中发生了一些变化,但我的大部分代码是相同的。
我已经检查并重新检查了所有特定于帐户的变量。为了测试这一点,我在本地机器上将它作为 ASP.NET MVC 4 Web 应用程序运行。
任何有关如何解决此问题的帮助或建议表示赞赏。如果我能提供更多可能有帮助的信息,请告诉我。谢谢阅读。