【问题标题】:How to POST JSON Data via HTTP API using VBScript?如何使用 VBScript 通过 HTTP API 发布 JSON 数据?
【发布时间】:2015-01-13 09:28:33
【问题描述】:

尝试向 HTTP API(PushBullet)发送 JSON POST 请求。但面临代码错误。任何帮助表示赞赏。 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

【问题讨论】:

    标签: json vbscript xmlhttprequest


    【解决方案1】:

    这里有点冒险,因为您认为没有必要包含实际的错误消息。您很可能在第 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
    

    【讨论】:

    • 非常感谢!对不起,我对 vbscript 很陌生!
    • 能否将其封装在子函数或函数中,并在需要时调用?
    • @NCollinsTE 当然。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2018-09-14
    • 2017-10-12
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多