如何使用VBScript通过HTTP API发布JSON数据?

时间:2014-11-16 11:08:19

标签: json vbscript xmlhttprequest

尝试将JSON POST请求发送到HTTP API(PushBullet)。但是在代码中面临错误。任何帮助赞赏。 Reference to the document to send push notification

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

1 个答案:

答案 0 :(得分:14)

在这里走出困境,因为您认为没有必要包含实际的错误消息。您最有可能在第3行中收到“无效字符”错误。这是因为您需要将JSON字符串定义为实际字符串。

改变这个:

strJSONToSend = {"type": "note", "title": "Alert", "body": "Lorem Ipsum Lorem Ipsum Lorem Ipsum."}

进入这个:

strJSONToSend = "{""type"": ""note"", ""title"": ""Alert"", ""body"": ""Lorem Ipsum Lorem Ipsum Lorem Ipsum.""}"

修改:作为旁注,如果您在代码中使用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