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

MS Access中VBA携带Bearer Token请求API返回未授权如何解决

问题原因
  • 授权Token值不匹配:VBA代码中赋值的strOwnerKey和curl命令内的有效Token存在字符差异,curl内的Token后缀为752xx,代码中漏写字符写成了75xx,Token校验不通过会直接返回未授权错误。
  • 请求头配置错误:代码中.SetRequestHeader "Content-type", "Accept"为无效配置,Accept头的字段名本身就是Accept,这行错误代码会把之前设置的Content-type覆盖为字符串"Accept",部分API服务端会因请求头格式异常直接拦截授权校验流程。
  • 编码规范问题:VBA中字符串拼接建议使用&运算符替代+,避免特殊值场景下出现隐式类型转换错误;原函数未设置返回值,在立即窗口调用时无法直接获取响应结果。
修正后的可运行代码
Function GetAuthorization()
    
    Dim objCurlHttp As Object
    Dim strResult As String
    Dim strWebServiceUrl As String
    Dim strOwnerKey As String
    
    ' Token需和curl命令内的值完全一致,不能漏写、多写字符
    strWebServiceUrl = "https://app.mysite.fr/api/v1/societe/11111111"
    strOwnerKey = "84dcc64aefabcdefghebcf7762752xx"
    
    Set objCurlHttp = CreateObject("MSXML2.serverXMLHTTP")
                                                          
    With objCurlHttp
        .Open "GET", strWebServiceUrl, False
        ' 修正错误的请求头配置
        .SetRequestHeader "cache-control", "no-cache"
        .SetRequestHeader "Accept", "application/json"
        .SetRequestHeader "Authorization", "Bearer " & strOwnerKey
        .Send
        
        strResult = .ResponseText
        Debug.Print strResult
    End With
    
    Set objCurlHttp = Nothing
    GetAuthorization = strResult
End Function
验证说明

替换正确Token、修正请求头后,VBA发起的请求和本地curl请求的报文结构完全一致,不会再返回Unauthorized错误。如果调整后仍报错,可以先打印拼接完成的Authorization头内容,和curl内的头信息逐字符比对,确认没有多余空格、转义字符问题即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 00:01:24