我需要通过调用 API 并通过 POST 传递 JSON 字符串来加载图像。 API 返回二进制 PNG 图像。
有从 URL 加载图像和发送 HTTP POST 请求的答案,但不是两者一起。
如何使用 VBA 从 Excel 向服务器发送 HTTP POST 请求?
更新: 这是我到目前为止的代码:
Sub LoadQR()
Dim d As Byte
JSON = Range("C5").Value
Set objHTTP = CreateObject("MSXML2.XMLHTTP")
Url = "https://xxxxxxx/xxxx/api/qr/v1/gen"
objHTTP.Open "POST", Url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send JSON
' Put response data into a file.
Open "qr.png" For Binary As #1
d = objHTTP.ResponseText
Put #1, 1, d
Close
' Load the data file as a picture.
Set myDocument = Worksheets(1)
myDocument.Shapes.AddPicture _
"qr.png", _
True, True, 500, 100, 70, 70
End Sub
获取类型不匹配,因为 API 响应实际上是二进制的,但
objHTTP.ResponseText
是一个字符串..有什么建议吗?
知道了:
Sub LoadQR()
Dim d() As Byte
JSON = Range("C5").Value
Set objHTTP = CreateObject("MSXML2.XMLHTTP")
Url = "https://xxxxxx/api/qr/v1/gen"
objHTTP.Open "POST", Url, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-Type", "application/json"
objHTTP.send JSON
Open "qr.png" For Binary As #1
d = objHTTP.ResponseBody
Put #1, 1, d
Close
Set myDocument = Worksheets(1)
myDocument.Shapes.AddPicture _
"qr.png", _
True, True, 450, 40, 200, 200
End Sub