我正在尝试使用Excel VBA从API获取令牌。当我编写编码值时,它工作得很好,就像这样(这只是一个示例,而不是真实值):
strEncoded = "nQvS3irniorrFE8fjoijBi8W43nS4e9jOJji"
但是当我尝试使用EncodeBase64函数时,它将返回错误400 Bad Request。 我比较了两个字符串,一个是由EncodeBase64生成的,另一个是我编写的,并且是相同的。我想念什么吗?
Public Sub XmlHttpTest()
Dim Json As Object
Dim tokenurl As String, strUser, strPassword As String
Dim strEncoded As String
Dim bearer As String, strDUE As String, strToEncode As String
Dim xmlhttp As New MSXML2.ServerXMLHTTP60
Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")
tokenurl = "https://apigateway.serpro.gov.br"
strUser = LTrim(RTrim(Sheet1.Cells(3, 4).Value))
strPassword = LTrim(RTrim(Sheet1.Cells(4, 4).Value))
strToEncode = strUser & ":" & strPassword
strEncoded = EncodeBase64(strToEncode)
xmlhttp.Open "POST", tokenurl, False
xmlhttp.setRequestHeader "Authorization", "Basic " & strEncoded
xmlhttp.send ("grant_type=client_credentials")
If Not xmlhttp.Status = 200 Then
MsgBox xmlhttp.statusText
Exit Sub
End If
Set Json = ParseJson(xmlhttp.responseText)
End Sub
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As MSXML2.DOMDocument60
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument60
Set objNode = objXML.createElement("b64")
objNode.DataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.text
Set objNode = Nothing
Set objXML = Nothing
End Function