Excel – Custom header with MSXML2.ServerXMLHTTP

excelserverxmlhttpvba

I am currently trying to use MSXML2.ServerXMLHTTP to send a POST http request.
I need to add a custom header "Auth" so that my requests get authorized but it doesn't seem to work.
Here is the code for my post function:

Function post(path As String, authToken As String, postData As String) As String
  Dim xhr As Object
  Dim message As String
On Error GoTo error:

  Set xhr = CreateObject("MSXML2.ServerXMLHTTP")
  xhr.Open "POST", path, False
  xhr.setRequestHeader "Content-Type", "application/json"
  xhr.setRequestHeader "Auth", authToken
  xhr.send postData

  If xhr.Status = 200 Then
    message = xhr.responseText
  Else
    message = xhr.Status & ": " & xhr.statusText
  End If

  Set xhr = Nothing
  post = message
error:
  Debug.Print "Error " & Err.Number; ":" & Err.Description
End Function

And I end up with "Error -2147012746 Requested Header was not found" (The message is actually translated since I use a different language on my computer).

However I didn't have this problem with the "Microsoft.XMLHTTP" Object.
Am I doing something wrong ?

Thank you for your time.

Best Answer

Try changing the call to SetRequestHeader to use a string literal. I duplicated the problem when authToken does not have a value set.

Change from this

xhr.setRequestHeader "Auth", authToken

To this

xhr.setRequestHeader "Auth", "testdatahere"
Related Topic