You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Sheets API V4旧令牌过期时如何获取新访问令牌(VB.NET)

VB.NET调用Google Sheets API V4令牌过期及空引用错误修复

问题分析

  • 空引用错误原因:手动实例化UserCredential时传入Nothing作为令牌参数,导致credential对象内部关键属性未初始化,调用API时触发System.NullReferenceException。
  • 令牌过期问题:原代码未实现自动刷新令牌逻辑,首次授权生成的访问令牌仅1小时有效期,过期后无法自动获取新令牌,必须重新授权。

修复方案

使用Google API客户端库提供的AuthorizationCodeInstalledApp来管理凭证,它会自动处理令牌的存储、刷新逻辑,无需手动维护令牌状态。

修复后的完整代码

' 谷歌表格数据范围
Dim rng As String = "Users!A1:D2"
' 定义Google Sheets API所需的权限范围
Dim scopes As IList(Of String) = New List(Of String)()
scopes.Add(Google.Apis.Sheets.v4.SheetsService.Scope.Spreadsheets)

' 加载client.json凭证文件
Dim credentialsFile As String = myClientjson
Dim credentialsStream As Stream = New FileStream(credentialsFile, FileMode.Open, FileAccess.Read)
Dim clientSecrets As GoogleClientSecrets = GoogleClientSecrets.FromStream(credentialsStream)

' 创建本地数据存储,用于持久化保存授权令牌(自动处理刷新令牌)
Dim datastore As IDataStore = New FileDataStore(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyCredentials"))

' 创建授权流程
Dim flow As New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With {
    .DataStore = datastore,
    .ClientSecrets = clientSecrets.Secrets,
    .Scopes = scopes
})

' 通过授权应用获取用户凭证:首次运行弹出浏览器引导授权,后续自动读取存储的令牌并刷新
Dim codeReceiver As ICodeReceiver = New LocalServerCodeReceiver()
Dim authApp As New AuthorizationCodeInstalledApp(flow, codeReceiver)
Dim credential As UserCredential = authApp.AuthorizeAsync("user", CancellationToken.None).Result

' 初始化Sheets服务
Dim service As New SheetsService(New BaseClientService.Initializer() With {
    .HttpClientInitializer = credential,
    .ApplicationName = "testApp"
})

' 发起数据请求并执行
Dim request = service.Spreadsheets.Values.Get(spreadsheetId, rng)
Dim response As ValueRange = request.Execute()

关键修复说明

  • 替换手动实例化UserCredential的错误代码,改用AuthorizationCodeInstalledApp.AuthorizeAsync获取凭证:
    1. 首次运行自动弹出浏览器引导用户完成授权
    2. 将授权后的刷新令牌、访问令牌保存到指定的本地数据存储中
    3. 后续运行自动读取存储的令牌,当访问令牌过期时自动调用刷新接口获取新令牌,无需用户重复授权

内容的提问来源于stack exchange,提问作者Duong Sansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:02:22