如何在VBA中为Get和Post Request传递API密钥?

时间:2018-05-05 02:22:10

标签: vba api

我正在使用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尝试时,它运行良好,当我转到开发工具授权密钥不同时,我想我错过了一些编码。有人可以帮忙吗

由于

2 个答案:

答案 0 :(得分:0)

我发现了..我缺少编码密钥

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

答案 1 :(得分:0)

基本身份验证要求用户名和密码一起进行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编码。