Home » excel » excel – Sending JSON object as a POST request

excel – Sending JSON object as a POST request

Posted by: admin April 16, 2020 Leave a comment

Questions:

I’m trying to send a JSON object from a VBA application in Excel. The code below sends the request correctly, however I can’t figure out how to make the request with the JSON object in the body.

Sub Post()

    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "http://localhost:3000/test"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-type", "application/x-www-form-      urlencoded"
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
    objHTTP.send ("test=6")

End Sub

If I try for instance to send “{test:6, test2: 7}” and log the body of the request on the server I get { ‘{parts:6, test: 7}’: ” }

How to&Answers:

As you probably already know, JSON structure can really produce serious headaches. In your case, I would say its all about the quotes, as you can see in here if you try to validate your {test:6, test2: 7}.

Try the following code. It looks plausible to me:

Sub Post()

Dim URL As String, JSONString As String, objHTTP as Object

    Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "http://localhost:3000/test"
    objHTTP.Open "POST", URL, False
    objHTTP.setRequestHeader "Content-type", "application/x-www-form-      urlencoded"
    objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"

    JSONString = "{""test"": 6,""test2"":7}"

    objHTTP.Send JSONString

End Sub