Json – Can a classic ASP page using xmlhttp make a JSON request

asp-classicjsonxmlhttprequest

I am completely lost. I am trying to post to an API on a remote server from a classic asp page that uses vbscript. My code:

set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP") 
xmlhttp.open "POST", vURL, false 
xmlhttp.setRequestHeader "Content-type","application/json"
xmlhttp.setRequestHeader "Accept","application/json"
xmlhttp.send "email=asdf@hotmail.com&firstname=joe&lastname=smith"
vAnswer = xmlhttp.responseText  

I receive a response that the request is not in the expected format. Tech support informs me that the API expects JSON in the post body. Can I do this from server-side asp?

Best Answer

'Create a function
Function ASPPostJSON(url)

'declare a variable
Dim objXmlHttp

Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP")

'If the API needs userName and Password authentication then pass the values here
objXmlHttp.Open "POST", url, False, "User123", "pass123"
objXmlHttp.SetRequestHeader "Content-Type", "application/json"
objXmlHttp.SetRequestHeader "User-Agent", "ASP/3.0"

'send the json string to the API server
objXmlHttp.Send "{""TestId"": 012345,""Test1Id"": 123456,""Test123"": 37,""Type123"": ""Test_String"",""contact"": {""name"": ""FirstName LastName"",""Organization"": ""XYZ"",""phone"":""123456"",""emailAddress"": ""test@mail.com""}}"

'If objXmlHttp.Status = 200 Then
    ASPPostJSON = CStr(objXmlHttp.ResponseText)
'end if

'return the response from the API server
Response.write(ASPPostJSON)
Set objXmlHttp = Nothing

End Function

'call the function and pass the API URL
call ASPPostJSON("https://TheAPIUrl.com/")