TableFusion API NET无效凭证[401]

时间:2018-09-17 17:41:37

标签: vb.net google-fusion-tables

我正在使用StackOverflow中的以下代码来管理FusionTable:

API:

Imports Google.Apis.Auth.OAuth2
Imports Google.Apis.Fusiontables.v2
Imports Google.Apis.Services
Imports Google.Apis.Upload

凭据:

Dim scopes() As String = New String() {"oauth2:https://www.googleapis.com/auth/fusiontables"} 
Dim creds As GoogleCredential = GoogleCredential.FromStream(File.OpenRead("MYJASON.json")) 
creds.CreateScoped(scopes)

我尝试过:

Dim scopes() As String = New String() {FusiontablesService.Scope.Fusiontables}

但结果相同。

然后

Dim service As FusiontablesService = New FusiontablesService(New BaseClientService.Initializer With {
            .HttpClientInitializer = creds,
            .ApplicationName = "MYAPPLICATION"
})

然后

Dim result As TableResource = service.Table
If result IsNot Nothing Then
    Try
        Dim str As StreamReader = New StreamReader("MYFILE.csv")

        Dim UpStatus As IUploadProgress = service.Table.ReplaceRows("MYTABLE", str.BaseStream, "application/octet-stream").Upload()
        If UpStatus.Status = Google.Apis.Upload.UploadStatus.Failed Then
        Console.WriteLine(UpStatus.Exception)
        End If
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
Else
    Console.WriteLine("Error Initializer")
End If

错误:

service.Table.ReplaceRows
UpStatus.Status = Google.Apis.Upload.UploadStatus.Failed

ex.Message:

  

Google.Apis.Requests.RequestError无效的凭据[401]

怎么了?

我有一个API密钥,2个ID客户端OAuth 2.0和1个服务ID,无济于事。

1 个答案:

答案 0 :(得分:0)

这里是stackoverflow

1°)创建一个服务帐户密钥credencial
2°)下载JSON文件
3°)生成一个c#类。您可以使用(http://json2csharp.com/

在我的情况下,类名是“ JsonFileProperties”

4°)使用此代码

 Dim scopes() As String = New String() {FusiontablesService.Scope.Fusiontables}
 Dim json As String = File.ReadAllText("MY.json")
 Dim JsonProperties As JsonFileProperties = Newtonsoft.Json.JsonConvert.DeserializeObject(Of JsonFileProperties)(json)
 Dim credential = New ServiceAccountCredential(New ServiceAccountCredential.Initializer(JsonProperties.client_email) With {
                .Scopes = scopes
                }.FromPrivateKey(JsonProperties.private_key))

 Dim service As FusiontablesService = New FusiontablesService(New BaseClientService.Initializer With {
                .HttpClientInitializer = credential,
                .ApplicationName = "*******",
                .ApiKey = "MYAPIKEY"
            })

5°)要访问编辑表或更新表(编辑,删除,importraws等),请不要忘记允许已授权用户列表中JSON文件中的邮件发送到FusionTable