【问题标题】:How to pass API key in VBA for Get and Post Request?如何在 VBA 中传递 API 密钥以获取和发布请求?
【发布时间】:2018-05-05 10:38:46
【问题描述】:

我正在使用https://developer.companieshouse.gov.uk/api/docs/ 访问 API 我有我的 API 密钥,但是,我不确定如何从 VBA 传递它。到目前为止,我在下面尝试过

AuthKey = [Key received]

With CreateObject("Microsoft.XMLHTTP")
        .Open "GET", strUrl, False, authKey
        .SetRequestHeader "Content-Type", "application/json"
        .SetRequestHeader "Accept", "application/json"
        .SetRequestHeader "Authorization", "Basic " & AuthKey
        .Send
        response = .ResponseText
    End With

当我从他们的测试页面https://developer.companieshouse.gov.uk/document/docs/document/id/content/fetchDocument.html 尝试时,它运行良好,当我转到授权密钥不同的开发工具时,我想我缺少一些编码。有人可以帮忙吗

谢谢

【问题讨论】:

    标签: vba api


    【解决方案1】:

    基本身份验证要求用户名和密码一起使用 base 64 编码。您需要传递的 AuthKey 本质上是:

    def unencoded_auth = "[username]:[authkey]"
    def encoded_auth = *call-to-base64-encode-value*(unencoded_auth)
    

    然后你会替换

    "Basic " & AuthKey
    

    "Basic " & encoded_auth
    

    我会参考this post关于如何实现base64编码。

    【讨论】:

      【解决方案2】:

      我找到了..我缺少对密钥进行编码

      Function EncodeBase64(text As String) As String
        Dim arrData() As Byte
        arrData = StrConv(text, vbFromUnicode)
      
        Dim objXML As MSXML2.DOMDocument
        Dim objNode As MSXML2.IXMLDOMElement
      
        Set objXML = New MSXML2.DOMDocument
        Set objNode = objXML.createElement("b64")
      
        objNode.DataType = "bin.base64"
        objNode.nodeTypedValue = arrData
        EncodeBase64 = objNode.text
      
        Set objNode = Nothing
        Set objXML = Nothing
      End Function
      

      【讨论】:

      • 那么你把 .SetRequestHeader "Authorization", "Basic" & EncodeBase64(AuthKey) 放了吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2021-08-15
      • 2021-09-24
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多