在setRequestHeader中使用变量,为什么它们不起作用?

时间:2019-07-11 23:45:04

标签: vbscript asp-classic serverxmlhttp

编辑:问题已解决。由于某种原因,Base64Encode函数在输出字符串中插入了换行符,直到我做出响应,我才注意到这一点。编写输出并查看页面的源代码,而不是编译的页面。


我正在尝试将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字符串,显示“请求失败的身份验证”。

除了输入Base64编码的字符串外,如何获得一个被识别为有效字符串的变量?

我应该注意,我已经尝试用双引号(auth""包围Chr(34),但无济于事。

编辑: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

1 个答案:

答案 0 :(得分:2)

Base64Encode函数在输出字符串中添加了换行符,直到我做出响应,我才注意到这一点。编写输出并查看页面的源代码,而不是编译的页面。

始终记得查看原始数据,而不仅仅是查看显示的数据(即不喜欢我)