[英]Send a Post request with the current excel sheet as multi-part form data using vba
[英]How to send a form-data POST request with VBA in Excel using WinHTTPRequest
我正在使用FastAPI構建一個 API,它必須可以從 Excel VBA 訪問。 FastAPI 的 OAuth2 身份驗證機制要求我發送“表單數據”POST 請求,但我不知道如何使用 VBA 中的 WinHTTPRequest 來執行此操作。
I already have a function which get plain JSON from the API, but this is a GET function and I'm not sure where to specify the "form-data" part in the body, nor where to put the username and password key-value對。
這是一個簡單的 VBA GET 處理一些錯誤。 我將如何修改它以使用用戶名和密碼字段進行表單數據 POST?
Public Function getreq(url As String)
Dim req As WinHttpRequest
Dim JsonString As String
Dim jp As Object
Dim resp As String
Dim errorstring As String
Set req = New WinHttpRequest
' req.SetRequestHeaderxxx ?
' this is where auth will go via POST form-data username and password?
req.Open "GET", url
On Error GoTo errhand:
req.Send
resp = req.ResponseText
If resp = "Internal Server Error" Then
resp = "{'error': 'Internal server error'}"
End If
getreq = resp
Exit Function
errhand:
Select Case Err.Number
Case -2147012894 'Code for Timeout
getreq = "{'error': 'Request timeout'}"
Case -2147012891 'Code for Invalid URL
getreq = "{'error': 'Bad url'}"
Case -2147012867 'Code for Invalid URL
getreq = "{'error': 'Cannot establish connection'}"
Case Else 'Add more Errorcodes here if wanted
errorstring = "Errornumber: " & Err.Number & vbNewLine & "Errordescription: " & Error(Err.Number)
getreq = "{'error': '" & errorstring & "'}"
End Select
End Function
而不是打開一個 GET 請求req.Open "GET", url
您需要打開一個POST
req.Open "POST", url, False
然后,您可以使用setRequestHeader
設置您要發送的內容類型以及作為回報您接受的內容。
req.setRequestHeader "Content-Type", "multipart/form-data"
req.setRequestHeader "Accept", "application/xml"
對於授權,您還需要創建一個請求 header。 這取決於您的 API 使用什么。
req.setRequestHeader "Authorization:", "Bearer " & EncodeBase64("Your-access-token")
最后你發送你的請求
req.send (YourData)
看看這個答案,它顯示了multipart/form-data
的數據結構是如何生成的。
如果 WinHTTPRequest 不起作用,我建議嘗試以下操作
Set objHttp = CreateObject("MSXML2.ServerXMLHTTP.6.0")
URL = "https:///commercial/payments-processing/v1/test/token"
objHttp.Open "POST", URL, False
objHttp.setRequestHeader "Content-Type", "multipart/form-data"
objHttp.setRequestHeader "Accept", "application/xml"
objHttp.setRequestHeader "Authorization:", "Bearer [Access Token]"
objHttp.send (strPaylodValue)
strResponseStatus = objHttp.Status
strResponseText = objHttp.ResponseText
strResponseText = CStr(strResponseText)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.