2013-09-23 3 views
1

Je suis en train de se connecter à Google Analytics pour récupérer des informations et le mettre dans la base de données, mon code, jusqu'à présent, est la suivante:400 Bad Request lors de l'utilisation Google.Apis.Analytics.v3

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Net; 
using System.Security.Cryptography.X509Certificates; 
using System.Text; 
using System.Threading.Tasks; 

// Google API 
using DotNetOpenAuth.Messaging; 
using DotNetOpenAuth.OAuth2; 
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.Services; 
using Google.Apis.Util; 


namespace CCQ.GoogleToSharePoint 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      //This is the API url which we're storing to a string 
      string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(); 

      //For whatever reason, this is labelled wrong. It is the email address 
      //that you have added as a user to your Analytics account 

      string clientId = "<redacted>@gmail.com"; 


      //This is the physical path to the file we downloaded earlier 
      //To demonstrate this, I've kept the full path to my key file. 
      //Obviously, you will need to change this to match where you've 
      //stored yours. 
      string keyFile = @"<redacted>"; 

      //The password Google gives you, probably the same as the one below 
      string keyPassword = "notasecret"; 


      //Store the authentication description 
      AuthorizationServerDescription desc = GoogleAuthenticationServer.Description; 

      //Create a certificate object to use when authenticating 
      X509Certificate2 key = new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable); 

      //Now, we will log in and authenticate, passing in the description 
      //and key from above, then setting the accountId and scope 
      AssertionFlowClient client = new AssertionFlowClient(desc, key) 
      { 
       ServiceAccountId = clientId, 
       Scope = scope 
      }; 

      //Finally, complete the authentication process 
      //NOTE: This is the first change from the update above 
      OAuth2Authenticator<AssertionFlowClient> auth = 
       new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState); 

      //First, create a new service object 
      //NOTE: this is the second change from the update 
      //above. Thanks to James for pointing this out 
      AnalyticsService gas = new AnalyticsService(new BaseClientService.Initializer() { Authenticator = auth }); 

      //Create our query 
      //The Data.Ga.Get needs the parameters: 
      //Analytics account id, starting with ga: 
      //Start date in format YYYY-MM-DD 
      //End date in format YYYY-MM-DD 
      //A string specifying the metrics 
      DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:<redacted>", "2013-09-09", "2013-09-23", "ga:visitors"); 

      //Specify some addition query parameters 
      r.Dimensions = "ga:visitorType"; 
      r.Sort = "-ga:visitors"; 
      r.MaxResults = 5; 

      //Execute and fetch the results of our query 
      try 
      { 
       //Write the column headers 
       GaData d = r.Execute(); 

       foreach (var h in d.ColumnHeaders) 
       { 
        Console.WriteLine(h.Name); 
       } 

       //Write the data 
       foreach (var row in d.Rows) 
       { 
        Console.WriteLine(row[0] + " ------ " + row[1]); 
       } 
      } 
      catch (ProtocolException webEx) 
      { 
       Console.WriteLine("Protocol Exception: {0}\n\n", webEx.ToString()); 
       Console.WriteLine("Stack Trace: {0}", webEx.StackTrace); 

       throw; 
      } 

     } 
    } 
} 

Malheureusement je jette une erreur sur ma ligne d'exécution, celui-ci en particulier:

//Write the column headers 
GaData d = r.Execute(); 

L'erreur est lui-même:

une erreur est survenue lors de l'envoi un message direct ou obtenir la réponse.

Google's API documentation dit que 400: en-tête Bad réponse sera envoyée dans les conditions suivantes:

400 Bad Request Types de mauvaises demandes comprennent:

  • dimensions non valides et/ou métriques

  • Quantité: soit aucune métrique, soit trop de dimensions/métriques

  • Utilisation OU sur un filtre où un côté est une métrique et l'autre une dimension

  • syntaxe filtre non valide/segment de

  • dimension illégale/combinaison métrique ou un segment advanged

Cependant, d'après ce que j'ai vu, je ne rencontre aucun de ceux-là - donc je suis éternellement confus. Comment puis-je continuer à déboguer ce problème?

La trace de pile pour cette erreur est:

StackTrace " à Google.Apis.Requests.ClientServiceRequest`1.Execute() dans c: \ code.google.com \ Google-API- dotnet-client \ default_3 \ Outils \ Google.Apis.Release \ bin \ Debug \ output \ par défaut \ Src \ GoogleApis \ Apis \ Demandes \ ClientServiceRequest.cs: ligne 96 \ r \ n à CCQ.GoogleToSharePoint.Program.Main (String [] args) dans i: \ dev \ CCQ.GoogleToSharePoint \ CCQ.GoogleToSharePoint \ Program.cs: ligne 121 \ r \ n à System.AppDomain._nExecuteAssembly (RuntimeAssembly assembly, String [] args) \ r \ n au System.AppDomain.ExecuteAssembly (String assemblyFile, Evidence assemblySecurity, String [] args) \ r \ n à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() \ r \ n à System.Threading.ThreadHelper.ThreadStart_Context (état de l'objet) \ r \ n à System.Threading.ExecutionContext.RunInternal (ExecutionContext ExecutionContext, ContextCallback rappel, l'état de l'objet, Boolean preserveSyncCtx) \ r \ n à System.Threading.ExecutionContext.Run (ExecutionContext ExecutionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) \ r \ n à System.Threading.ExecutionContext.Run (ExecutionContext ExecutionContext, rappel ContextCallback, Object state) \ r \ n à System.Threading.ThreadHelper.ThreadStart() » string

+1

Avez-vous essayé de votre première requête de Google Analytics Explorateur de requêtes d'abord essayer ici http : //ga-dev-tools.appspot.c om/explorer / –

Répondre

1

J'ai tout le week-end vais Trough le même problème, et je trouvé la solution, essayez ce code pour moi :) travaillé

log4net.Config.XmlConfigurator.Configure();

 const string ServiceAccountUser = "[email protected]"; 
     AssertionFlowClient client = new AssertionFlowClient(
      GoogleAuthenticationServer.Description, new X509Certificate2(@"C:\xxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable)) 
     { 
      Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(), 
      ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId 
      //,ServiceAccountUser = ServiceAccountUser 
     }; 
     //OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState); 
     var authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState); 
     var service = new AnalyticsService(new BaseClientService.Initializer() 
     { 
      Authenticator = authenticator 
     }); 


     string profileId = "ga:63494033"; 
     string startDate = "2010-10-01"; 
     string endDate = "2010-10-31"; 
     string metrics = "ga:visits"; 
     DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics); 
     request.Dimensions = "ga:date"; 
     GaData data = request.Execute(); 
    }