将变量与 setRequestHeader 一起使用,为什么它们不起作用?

Using variables with setRequestHeader, why won't they work?

编辑:问题已解决。出于某种原因,Base64Encode 函数在输出字符串中放置了一个换行符,直到我 response.write 输出并查看页面的源代码而不是编译页面时我才注意到这一点。


我正在尝试将 JSON 发送到远程服务器以取回 JSON 响应(基本上我向他们发送数据,他们根据我的数据执行计算并发回不同的数据)。但是,服务器没有取回数据,而是告诉我请求验证失败。

身份验证涉及发送 base64 编码的字符串、用户名和密码组合。这些值可以改变,所以我使用变量来传递信息。这不起作用,但是如果我将完全编码的值作为字符串输入,它就会起作用。

Function GetAPdataPost(sSendHTML, sURL)
  dim apHTTP
  dim sHTTPResponse
  dim API_KEY
  dim API_PWD
  dim auth

  API_KEY     = "fred"
  API_PWD     = "barney"
  auth = Base64Encode(API_KEY & ":" & API_PWD)
  Set apHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
  apHTTP.Open "POST", sURL, false
  apHTTP.setRequestHeader "Content-Type", "application/json; charset=UTF-8" 
  apHTTP.setRequestHeader "Authorization","Basic ZnJlZDpiYXJuZXk=" '<-- works
  apHTTP.setRequestHeader "Authorization", "Basic " & auth '<-- doesn't work
  apHTTP.setRequestHeader "Content-Length", len(sSendHTML)
  apHTTP.setRequestHeader "Accept", "*/*"
  apHTTP.setRequestHeader "Account-Number", "00000004"
  apHTTP.setRequestHeader "Cache-Control", "no-cache"
  apHTTP.setRequestHeader "Connection", "close"

  On Error Resume Next
  apHTTP.send sSendHTML

  sHTTPResponse = apHTTP.responseText

  If Err.Number = 0 Then
    GetAPdataPost = sHTTPResponse
  Else
    GetAPdataPost = "Something went wrong: " & Err.Number
  End If
  On Error Goto 0

  Set apHTTP = Nothing
End Function

使用第一行会得到服务器的正确响应,一个包含所有必需数据的有效 JSON 字符串。第二行导致 JSON 字符串表示 "The request failed authentication".

那么除了输入 Base64 编码的字符串之外,我如何让一个变量被识别为有效的字符串?

我应该注意到,我曾尝试用双引号 ("") 和 Chr(34)auth 括起来,但没有用。

编辑:Base64 编码函数。

Function Base64Encode(sText)
    Dim oXML, oNode

    Set oXML = CreateObject("Msxml2.DOMDocument.3.0")
    Set oNode = oXML.CreateElement("base64")
    oNode.dataType = "bin.base64"
    oNode.nodeTypedValue =Stream_StringToBinary(sText)
    Base64Encode = oNode.text
    Set oNode = Nothing
    Set oXML = Nothing
End Function

Function Stream_StringToBinary(Text)
  Const adTypeText = 2
  Const adTypeBinary = 1

  'Create Stream object
  Dim BinaryStream 'As New Stream
  Set BinaryStream = CreateObject("ADODB.Stream")

  'Specify stream type - we want To save text/string data.
  BinaryStream.Type = adTypeText

  'Specify charset For the source text (unicode) data.
  BinaryStream.CharSet = "us-ascii"

  'Open the stream And write text/string data To the object
  BinaryStream.Open
  BinaryStream.WriteText Text

  'Change stream type To binary
  BinaryStream.Position = 0
  BinaryStream.Type = adTypeBinary

  'Ignore first two bytes - sign of
  BinaryStream.Position = 0

  'Open the stream And get binary data from the object
  Stream_StringToBinary = BinaryStream.Read

  Set BinaryStream = Nothing
End Function

Base64Encode 函数在输出字符串中放置了一个换行符,直到我 response.write 输出并查看页面的源代码而不是编译页面时我才注意到这一点。

永远记得看原始数据,而不仅仅是显示的数据(即不像我)