尝试通过.NET连接到Google AnalyticsAPI会出现“400 Bad Request”

时间:2013-03-01 17:38:56

标签: .net vb.net google-analytics-api

我正在尝试从.NET应用程序连接到Google AnalyticsAPI。这是我提出的代码:

Public Function GetData() As String   
    Dim client As AssertionFlowClient = New AssertionFlowClient(GoogleAuthenticationServer.Description,
                                                                New X509Certificate2("C:\Users\xxxxx\privatekey.p12", "notasecret",
                                                                                     X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.MachineKeySet)) With {
                                                                .Scope = "analytics.readonly",
                                                                .ServiceAccountId = "xxxxx@developer.gserviceaccount.com"}
    Dim authenticator As OAuth2Authenticator(Of AssertionFlowClient) = New OAuth2Authenticator(Of AssertionFlowClient)(client, AddressOf AssertionFlowClient.GetState)
    Dim service As AnalyticsService = New AnalyticsService(authenticator)

    Dim profileId As String = "ga:xxxxx"
    Dim startDate As String = "2013-02-15"
    Dim endDate As String = "2013-02-20"
    Dim metrics As String = "ga:visitors"

    Dim request As DataResource.GaResource.GetRequest = service.Data.Ga.Get(profileId, startDate, endDate, metrics)
    Dim data As GaData = request.Fetch()

    Return data.ToString()
End Function

我的问题是,当我点击此方法时,我在request.Fetch()行上收到一条异常,说明“发送直接消息或获取响应时出错”。内部异常说:“远程服务器返回错误:(400)错误请求。”

这个错误显然很模糊。根据{{​​3}},400 Bad Request表示输入参数在某种程度上没有意义。任何人都可以通过查看我的代码中的参数来诊断问题吗?否则,我怎么能开始追踪我做错了什么?错误中几乎没有信息。

(至少我已经过了认证阶段......我认为。)

1 个答案:

答案 0 :(得分:1)

this answer广泛借用,我提出的解决方案是:

Imports System.Security.Cryptography.X509Certificates
Imports Google.Apis.Analytics.v3
Imports Google.Apis.Analytics.v3.Data
Imports Google.Apis.Authentication.OAuth2
Imports Google.Apis.Authentication.OAuth2.DotNetOpenAuth
Imports System.Security.Cryptography

Public Class GoogleAnalytics

    Private _profileId As String
    Private _service As AnalyticsService

    ''' <summary>
    ''' Creates an instance of the Google Analytics interface
    ''' </summary>
    ''' <param name="profileId">The Google Analytics profile ID, in the form "ga:123456789". This is *not* the same as the ID number used in the GA JavaScript to initialize the tracking! The number you want is in Google Analytics > Admin > (your profile) > Profile Settings.</param>
    ''' <param name="serviceAccountId">The e-mail address of the Service Account that will access the API. These accounts can be generated from the Google API Console and then authorized by adding the e-mail address to the list of authorized users in Google Analytics.</param>
    ''' <param name="privateKeyPath">The path to the private-key (.p12) file from Google.</param>
    ''' <param name="certificatePassword">The password for the private key. Probably "notasecret".</param>
    ''' <remarks>Once created, this GoogleAnalytics object can be used to make an arbitrary number of requests.</remarks>
    Public Sub New(profileId As String, serviceAccountId As String, privateKeyPath As String, certificatePassword As String)
        Dim cert As X509Certificate2 = New X509Certificate2(privateKeyPath, certificatePassword, X509KeyStorageFlags.Exportable Or X509KeyStorageFlags.MachineKeySet)
        Dim client As AssertionFlowClient = New AssertionFlowClient(GoogleAuthenticationServer.Description, cert) With {.Scope = "https://www.googleapis.com/auth/analytics.readonly",
                                                                                                                        .ServiceAccountId = serviceAccountId}
        Dim authenticator As OAuth2Authenticator(Of AssertionFlowClient) = New OAuth2Authenticator(Of AssertionFlowClient)(client, AddressOf AssertionFlowClient.GetState)
        _service = New AnalyticsService(authenticator)

        _profileId = profileId
    End Sub

    Public Function GetData(startDate As String, endDate As String, metrics As String, dimensions As String, Optional filters As String = Nothing) As GaData
        Dim request As DataResource.GaResource.GetRequest = _service.Data.Ga.Get(_profileId, startDate, endDate, metrics)
        request.Dimensions = dimensions

        If filters IsNot Nothing Then
            request.Filters = filters
        End If

        Return request.Fetch()
    End Function

End Class

这是一个独立的类,可以按如下方式使用:

Dim analytics As New GoogleAnalytics("ga:12345678", "123456789012@developer.gserviceaccount.com", "C:\privatekey.p12", "notasecret")
Dim data as GaData = analytics.GetData(DateTime.Now.AddDays(-30).ToString("yyyy-MM-dd"),
                                       DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"),
                                       "ga:totalEvents",
                                       "ga:eventCategory,ga:eventAction")

我发现的最大问题是个人资料ID。这是您传递给Google的Javascript跟踪代码的ID号;相反,它是您在Google Analytics&gt;中找到的数字。管理员&gt; (您的个人资料)&gt;档案设置。希望这有助于其他人!