如何使用 VBScript 通过 HTTP API POST JSON 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26956256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to POST JSON Data via HTTP API using VBScript?
提问by Rajandran R
Trying to Send JSON POST Request to an HTTP API(PushBullet). But facing error in the code. Any help appreciated. Reference to the document to send push notification
尝试将 JSON POST 请求发送到 HTTP API(PushBullet)。但面临代码中的错误。任何帮助表示赞赏。参考文档发送推送通知
Dim objXmlHttpMain , URL
strJSONToSend = {"type": "note", "title": "Alert", "body": "Lorem Ipsum Lorem Ipsum Lorem Ipsum."}
URL="https://api.pushbullet.com/v2/pushes"
Set objXmlHttpMain = CreateObject("Msxml2.ServerXMLHTTP")
on error resume next
objXmlHttpMain.open "POST",URL, False
objXmlHttpMain.setRequestHeader "Authorization", "Bearer <api secret id>"
objXmlHttpMain.setRequestHeader "Content-Type", "application/json"
objXmlHttpMain.send strJSONToSend
set objJSONDoc = nothing
set objResult = nothing
回答by Ansgar Wiechers
Going out on a limb here, since you didn't deem it necessary to include the actual error message. You're most likely getting an "invalid character" error in line 3. That's because you need to define your JSON string as an actual string.
在这里冒险,因为您认为没有必要包含实际的错误消息。您很可能在第 3 行收到“无效字符”错误。那是因为您需要将 JSON 字符串定义为实际字符串。
Change this:
改变这个:
strJSONToSend = {"type": "note", "title": "Alert", "body": "Lorem Ipsum Lorem Ipsum Lorem Ipsum."}
into this:
进入这个:
strJSONToSend = "{""type"": ""note"", ""title"": ""Alert"", ""body"": ""Lorem Ipsum Lorem Ipsum Lorem Ipsum.""}"
Edit:As a side-note, if you're using On Error Resume Nextin your code alwaysput proper error handling in place, and also keep it as localized as possible:
编辑:作为旁注,如果您On Error Resume Next在代码中使用,请始终进行适当的错误处理,并尽可能使其本地化:
On Error Resume Next 'enable error handling
objXmlHttpMain.open "POST",URL, False
If Err Then 'handle errors
WScript.Echo Err.Description & " [0x" & Hex(Err.Number) & "]"
WScript.Quit 1
End If
On Error Goto 0 'disable error handling again

