执行请求失败:https://docs.google.com/feeds/default/private/full?max-results = 200

时间:2015-06-18 06:24:10

标签: c# oauth google-api google-drive-api google-oauth

我正在尝试使用以下代码获取google驱动器文件列表但我收到了错误消息 执行请求失败:https://docs.google.com/feeds/default/private/full?max-results=2000

之前它正在运作但是从最近几个月起它无法正常工作我无法理解我哪里出错了。请帮助我

OAuth2Parameters parameters = new OAuth2Parameters()
    {
        ClientId = "MYID.apps.googleusercontent.com",
        ClientSecret = "MYSECREAT",
        RedirectUri = currentURL,//"http://localhost:6692/Home.html"
        Scope = "https://docs.google.com/feeds/ ",
        State = "documents",
        AccessType = "offline",//offline means it creats a refreshtoken 
        TokenExpiry = DateTime.Now.AddYears(1)
    };
parameters.AccessCode = code;
Google.GData.Client.OAuthUtil.GetAccessToken(parameters);

GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "NAME", parameters);
DocumentsService service = new DocumentsService("NAME");
service.RequestFactory = requestFactory;
//requestFactory.CustomHeaders["Authorization"] = "Bearer " + parameters.AccessToken;
DocumentsListQuery query = new DocumentsListQuery();
query.NumberToRetrieve = 2000;

// Make a request to the API and get all documents.
//I Got an error in following line
DocumentsFeed feed = service.Query(query);

1 个答案:

答案 0 :(得分:3)

您的部分问题是您正在使用旧的Gdata调用。虽然旧的GData API仍然很难让它与Oauth2一起工作,因为你不能再使用客户端登录了,而且当客户端登录是一个选项时它就会被恢复。

我建议使用使用新Google Drive Rest API

的Google .net客户端库

PM> Install-Package Google.Apis.Drive.v2

与Oauth2类连接:

/// <summary>
        /// Authenticate to Google Using Oauth2
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientId">From Google Developer console https://console.developers.google.com</param>
        /// <param name="clientSecret">From Google Developer console https://console.developers.google.com</param>
        /// <param name="userName">A string used to identify a user.</param>
        /// <returns></returns>
        public static DriveService AuthenticateOauth(string clientId, string clientSecret, string userName)
        {

            //Google Drive scopes Documentation:   https://developers.google.com/drive/web/scopes
            string[] scopes = new string[] { DriveService.Scope.Drive,  // view and manage your files and documents
                                             DriveService.Scope.DriveAppdata,  // view and manage its own configuration data
                                             DriveService.Scope.DriveAppsReadonly,   // view your drive apps
                                             DriveService.Scope.DriveFile,   // view and manage files created by this app
                                             DriveService.Scope.DriveMetadataReadonly,   // view metadata for files
                                             DriveService.Scope.DriveReadonly,   // view files and documents on your drive
                                             DriveService.Scope.DriveScripts };  // modify your app scripts


            try
            {
                // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
                                                                                             , scopes
                                                                                             , userName
                                                                                             , CancellationToken.None
                                                                                             , new FileDataStore("Daimto.Drive.Auth.Store")).Result;

                DriveService service = new DriveService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Daimto Drive API Sample",
                });
                return service;
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.InnerException);
                return null;

            }

        }

连接

  // Connect with Oauth2 Ask user for permission
            String CLIENT_ID = "xxx-d0vpdthl4ms0soutcrpe036ckqn7rfpn.apps.googleusercontent.com";
            String CLIENT_SECRET = "NDmluNfTgUk6wgmy7cFo64RV";      
            DriveService service = Authentication.AuthenticateOauth(CLIENT_ID, CLIENT_SECRET, Environment.UserName);

列出文件方法:

 /// Documentation Search: https://developers.google.com/drive/web/search-parameters
        /// </summary>
        /// <param name="service">a Valid authenticated DriveService</param>        
        /// <param name="search">if Search is null will return all files</param>        
        /// <returns></returns>
        public static IList<File> GetFiles(DriveService service, string search)
        {

            IList<File> Files = new List<File>();

            try
            {
                //List all of the files and directories for the current user.  
                // Documentation: https://developers.google.com/drive/v2/reference/files/list
                FilesResource.ListRequest list = service.Files.List();
                list.MaxResults = 1000;
                if (search != null)
                {
                    list.Q = search;
                }
                FileList filesFeed = list.Execute();

                //// Loop through until we arrive at an empty page
                while (filesFeed.Items != null)
                {
                    // Adding each item  to the list.
                    foreach (File item in filesFeed.Items)
                    {
                        Files.Add(item);
                    }

                    // We will know we are on the last page when the next page token is
                    // null.
                    // If this is the case, break.
                    if (filesFeed.NextPageToken == null)
                    {
                        break;
                    }

                    // Prepare the next page of results
                    list.PageToken = filesFeed.NextPageToken;

                    // Execute and process the next page request
                    filesFeed = list.Execute();
                }
            }
            catch (Exception ex) {
                // In the event there is an error with the request.
                Console.WriteLine(ex.Message);                            
            }
            return Files;
        }

列出文件:

 // Listing files with search.  
                // This searches for a directory with the name DiamtoSample
                string Q = "title = 'DiamtoSample' and mimeType = 'application/vnd.google-apps.folder'";
                IList<File> _Files = DaimtoGoogleDriveHelper.GetFiles(service, Q);

                foreach (File item in _Files)
                {
                    Console.WriteLine(item.Title + " " + item.MimeType);
                }

有用的链接