我想用一些 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, 等等}
我的oHttp.Send
行一定是错误的,一旦我添加更多参数,我就会收到编译器错误
我发布这个(不起作用)代码是因为它是迄今为止我在网络上找到的最好的代码(所有其他代码都让我陷入了我不明白的其他事情......
我还尝试将 json 代码放入单元格中,将单元格放入字符串中,然后像这样发送字符串:oHttp.Send
(字符串),这会产生 错误 406 Not Acceptable
来自网站的回复。
最佳答案
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
关于json - 在 Excel VBA 中将 JSON 发布到网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21021540/