在excel vba中将JSON发布到Web

时间:2014-01-09 13:25:16

标签: json post excel-vba vba excel

我想用一些VBA发布一些JSON:

Dim sURL As String, sHTML As String, sAllPosts As String
Dim oHttp As Object
Dim blWSExists As Boolean
Set oHttp = CreateObject("MSXML2.XMLHTTP")
sURL = "some webste.com"
oHttp.Open "POST", sURL, False
oHttp.setRequestHeader "Content-type", "application/json"
oHttp.setRequestHeader "Accept", "application/json"
oHttp.Send (mType = OPEN_SYSTEM_TRADE & systemOwnerId = 10)
sHTML = oHttp.ResponseText
Worksheets("Open1").Range("A1").Value = sHTML

要发送到网站的预定义格式是json中的描述如下: {"mType":"OPEN_SYSTEM_TRADE","systemOwnerId":10,"systemId":16, etc}

我的oHttp.Send行必定是错误的,只要我添加更多参数,我就会遇到编译错误 我发布这个(不工作)代码导致它到目前为止我在网上找到的最好的(所有其他让我卡在其他我不理解的东西上......

我还尝试将json代码放在​​一个单元格中,将单元格放在一个字符串中,并发送如下字符串:oHttp.Send(字符串),这会导致Error 406 Not Acceptable来自网站。

1 个答案:

答案 0 :(得分:14)

JSON可能对格式化方式非常敏感,因此我会确保在发送之前所有内容都被正确引用。我建议在发送之前将Body拆分为单独的变量并使用http://jsonformatter.curiousconcept.com/调试该值。

Dim Body As String
Body = "{""mType"":""OPEN_SYSTEM_TRADE"",""systemOwnerId"":10}"

' Set breakpoint here, get the Body value, and check with JSON validator
oHttp.Send Body

在使用Salesforce的REST API时,我遇到了许多类似的问题,并将我的工作合并到一个可能对您有用的库中:https://github.com/VBA-tools/VBA-Web。使用此库,您的示例如下所示:

Dim Body As New Dictionary
Body.Add "mType", "OPEN_SYSTEM_TRADE"
Body.Add "systemOwnerId", 10

Dim Client As New WebClient
Dim Response As WebResponse
Set Response = Client.PostJson("somewebsite.com", Body)

Worksheets("Open1").Range("A1").Value = Response.Content