【发布时间】:2017-12-16 06:35:22
【问题描述】:
我一直在尝试编写一些自定义代码,在其中搜索我拥有的特定字符串的 Google 表格文件。现在我有这个工作,我使用 ApiKey 进行了身份验证,一切正常,但是!!!我必须将文件的隐私更改为“使用 url 公开”才能工作。我认为这不太对...
然后我进入下一步,遍历文件夹及其子文件夹中的所有文件,并在所有文件中搜索该字符串,这就是我遇到问题的地方......
string ApplicationName = "My App Name";
string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
// Create Google Sheets API service.
var service = new DriveService(new BaseClientService.Initializer
{
ApplicationName = ApplicationName,
ApiKey = AppSettings.GetValue(AppSettings.API_KEY)
});
String folderId = "folder_id";
ChildrenResource.ListRequest request = service.Children.List(folderId);
do
{
try
{
ChildList children = request.Execute();
foreach (ChildReference child in children.Items)
{
Console.WriteLine("File Id: " + child.Id);
}
request.PageToken = children.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
request.PageToken = null;
}
} while (!String.IsNullOrEmpty(request.PageToken));
我收到了这个错误:
Google.Apis.Requests.RequestError
Login Required [401]
Errors [
Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]
]
相同的 API 密钥是我用于检查单个文件是否有字符串的另一块代码的那个。不同之处以及我认为问题出在哪里,我想要迭代文件的文件夹与我共享(我不是专有的,但我拥有它的完全访问权限)。我还尝试将其隐私更改为公开,但没有结果。
你知道我收到了这个错误吗?我没有任何线索。
解决方案:
string ApplicationName = "My App Name";
string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DriveFile };
ClientSecrets secrets = new ClientSecrets()
{
ClientId = ""MY_CLIENT_ID,
ClientSecret = "MY_CLIENT_SECRET"
};
var token = new TokenResponse
{
AccessToken = "MY_ACCESS_TOKEN",
RefreshToken = "MY_REFRESH_TOKEN"
};
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets
}),
"user",
token);
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credentials,
ApplicationName = ApplicationName
});
return service;
我从OAuth2 Playground 获得的所有令牌和密钥都很容易理解。还要感谢这个人answer。
【问题讨论】:
标签: c# .net google-sheets google-api google-drive-api