【问题标题】:Visual Basic sent data to api as json objectVisual Basic 将数据作为 json 对象发送到 api
【发布时间】:2021-07-05 04:49:35
【问题描述】:

美好的一天,我正在尝试将数据作为 json 对象发送到 api

   "Content-Type: application/json" 
  "Authorization: Bearer $ACCESS_TOKEN" 
 -d '[ 
       { 
           "datetime": "2021-02-21 14:07:37", 
           "isRefund": false, 
           "receiptNumber": "880090", 
           "amount": 164.22 
       } 
   ]' 

这是我的代码:

Sub X2()
'  Dim xhr As Object
  
Set xhr = CreateObject("MSXML2.ServerXMLHTTP")
  xhr.Open "POST", "https://tenanttest.api.rubixpark.com/api/v1/sales", False

  xhr.setRequestHeader "Content-Type", "application/json"
  xhr.setRequestHeader "Authorization", "Bearer " + accesstoken

  xhr.setRequestHeader "datetime", Now()
  xhr.setRequestHeader "isRefund", False
  xhr.setRequestHeader "receiptNumber", 111
  xhr.setRequestHeader "amount", Format(1000#, "##,##0.00")
  xhr.send
  
  If xhr.Status = 200 Then
   MsgBox xhr.ResponseText

  Else
  End If


End Sub

所以我想只在标题和正文上的其他数据上发送访问令牌作为 json 对象,如第一个代码块任何帮助和感谢

【问题讨论】:

  • 注意,您的第一个示例实际上发送了一个 array,其中包含一个对象,而不是直接发送对象。
  • github.com/VBA-tools/VBA-JSON 通常建议在 VBA 中使用 JSON。

标签: vba api


【解决方案1】:

看起来像这样:

Dim xhr As Object

Set xhr = CreateObject("MSXML2.ServerXMLHTTP")
xhr.Open "POST", "https://tenanttest.api.rubixpark.com/api/v1/sales", False

xhr.setRequestHeader "Content-Type", "application/json"
xhr.setRequestHeader "Authorization", "Bearer " + accesstoken
xhr.send "[{""datetime"": ""2021-02-21 14:07:37"",""isRefund"": false," & _
         """receiptNumber"": ""880090"",""amount"": 164.22}]"

If xhr.Status = 200 Then
    MsgBox xhr.ResponseText
End If

【讨论】:

  • 添加日期时间值时出现日期时间问题,感谢您的帮助
  • 您可以使用Format() 来获取您需要插入的字符串。例如:Format(Now, "yyyy-mm-dd hh:nn:ss")
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-26
  • 2012-12-01
  • 1970-01-01
  • 2018-03-21
  • 2019-05-06
  • 1970-01-01
  • 2017-03-09
相关资源
最近更新 更多