2014-09-05 87 views
0

每次我连接到谷歌驱动器它抛出WebException 401未经授权。oAuth2.0的谷歌驱动器C#WPF

WebClient wC = new WebClient(); 
    var down = wC.DownloadString("https://www.googleapis.com/drive/v2/about?includeSubscribed=true&key=[api-key]"); 
    JObject o = JObject.Parse(down); 

    Console.WriteLine("Name, " +o["name"]); 
    Console.ReadLine(); 

我想创建C#桌面应用程序。

回答

0

您可以使用此代码

UserCredential credential; 
     try 
     {     
      using (var stream = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "client_secrets.json"), FileMode.Open, FileAccess.Read)) 
      { 
       credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
        GoogleClientSecrets.Load(stream).Secrets, 
        new[] { DriveService.Scope.DriveFile, DriveService.Scope.Drive }, 
        acocuntAddress, CancellationToken.None, new FileDataStore("Drive.Auth.Store")).Result; 

      }    
      var service = new DriveService(new BaseClientService.Initializer() 
      { 
       HttpClientInitializer = credential, 
       ApplicationName = "OutlookPlugin", 
      });    
      //give list of files 
       var items = service.Files.List().Execute().Items; 
0

你应该发送一个验证头与你的网页请求。我有自己的开源轻量级库,可以简化Google Drive上文件的使用:https://github.com/AlexeyVlg/Pranas.Net.Clouds您不需要使用它,但在此库中,可以找到有关如何使用RestSharp库获取授权令牌的示例:https://github.com/AlexeyVlg/Pranas.Net.Clouds/blob/master/Pranas.Client.GoogleDrive/Business/Auth/DriveAuthorization.cs。只需下载C#WPF示例并尝试一下。 请记住在DriveAuthData类中指定您的AppClientId,AppClientSecret和AppClientRedirectUri以使用此示例。 有关授权的更多信息,请访问:https://developers.google.com/drive/web/about-auth