简体   繁体   中英

How do I pass more than one JSON parameters like headers to Post Request in VBA?

I am able to attach a header but I am also trying to pass the parameters in form of dictionary to get the PostRequest in VBA.

**parameters to pass**
headers = {some headers}
files = {'upload_file': 'myfile.csv'}
data = {"key1": "value1","key2": "value2"}

*I need to do something similar like this as we do in other language like python*
requests.post(url, headers=header, data=data, files=files)

**vba code** 
With req
        .Open "POST", reqURL, False
        .setRequestHeader "Accept", "Application/json"
        .send
End With

I am using MSXML2.XMLHTTP60 as a req variable

Try concatenating the parameters with ;

    Dim fso As Object, ts As Object, data As String, files As String
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.opentextfile("myfile.csv", 1)
    files = "{'upload_file': '" & ts.readAll & "'}"
    ts.Close

    data = "{'key1': 'value1','key': 'value2'}"

    With req
        .Open "POST", URL, False
        .setRequestHeader "Accept", "Application/json"
        .send "data=" & data & ";files=" & files
        Debug.Print .responseText
    End With

The python code is posting multipart/form-data so it gets a bit more complicated

Option Explicit

Sub postjson()

    Const reqURL = "http://clougo.at/api/trading"
    Const CSV_FILE = "input.csv"
    Const token = "1|WZeEXorNG6qWVmr8zj80PrkrhiFcMupj1NMwj7Nh"
    
    Dim data As Object, key
    Set data = CreateObject("Scripting.Dictionary")
    data.Add "product", "POWER"
    data.Add "valid_until", "2021-09-07"
    data.Add "market_area", "DE"
    
    ' generate boundary
    Dim BOUNDARY, s As String, n As Integer
    For n = 1 To 16: s = s & Chr(65 + Int(Rnd * 25)): Next
    BOUNDARY = s & CDbl(Now)

    Dim part As String, ado As Object
    For Each key In data.keys
        part = part & "--" & BOUNDARY & vbCrLf
        part = part & "Content-Disposition: form-data; name=""" & key & """" & vbCrLf & vbCrLf
        part = part & data(key) & vbCrLf
    Next
    ' filename
    part = part & "--" & BOUNDARY & vbCrLf
    part = part & "Content-Disposition: form-data; name=""upload_file""; filename=""" & CSV_FILE & """" & vbCrLf & vbCrLf
    
    ' read csv file as binary
    Dim csv
    Set ado = CreateObject("ADODB.Stream")
    ado.Type = 1 'binary
    ado.Open
    ado.LoadFromFile CSV_FILE
    ado.Position = 0
    csv = ado.read
    ado.Close

    ' combine part, csv , end
    ado.Open
    ado.Position = 0
    ado.Type = 1 ' binary
    ado.Write ToBytes(part)
    ado.Write csv
    ado.Write ToBytes(vbCrLf & "--" & BOUNDARY & "--")
    ado.Position = 0

    Dim req As New MSXML2.XMLHTTP60
    With req
        .Open "POST", reqURL, False
        .setRequestHeader "Accept", "Application/json"
        .setRequestHeader "Authorization", "Bearer " & token
        .setRequestHeader "Content-Type", "multipart/form-data; boundary=" & BOUNDARY
        .send ado.read
        Debug.Print .responseText
    End With

End Sub

Function ToBytes(str As String) As Variant

    Dim ado As Object
    Set ado = CreateObject("ADODB.Stream")
    ado.Open
    ado.Type = 2 ' text
    ado.Charset = "_autodetect"
    ado.WriteText str
    ado.Position = 0
    ado.Type = 1
    ToBytes = ado.read
    ado.Close

End Function


    Dim req As New MSXML2.XMLHTTP60
    Dim reqURL As String
    Dim fso, ts As Object
    Dim data As String, files As String
    
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.OpenTextFile("C:\Users\mypath\input.csv", 1)
    files = "{'upload_file': '" & ts.ReadAll & "'}"
    'Debug.Print files
    ts.Close
    
    data = "{'product':'POWER','valid_unil':'2021-09-07','market_area':'DE'}"
    'Debug.Print data
    
    reqURL = "http://clougo.at/api/trading"
    
    token = "1|WZeEXorNG6qWVmr8zj80PrkrhiFcMupj1NMwj7Nh"
    
    With req
        .Open "POST", reqURL, False
        '.setRequestHeader "Content-Type", "application/json"
        .setRequestHeader "Authorization", "Bearer" & token
        .setRequestHeader "Accept", "Application/json"
        .send "data=" & data & ";files=" & files
    End With
    
    Debug.Print req.Status

End Sub

the response is 401

here is the working python code

import requests


url = "http://clougo.at/api/trading"
csv_file = "input.csv"

auth_token = "1|WZeEXorNG6qWVmr8zj80PrkrhiFcMupj1NMwj7Nh"
header = {'Authorization': 'Bearer ' + auth_token, 'Accept': 'application/json'}

files = {'upload_file': open(csv_file, 'rb')}

data = {
"product": "POWER",
"valid_unil": "2021-09-07",
"market_area": "DE"
}
r = requests.post(url, headers=header, data=data, files=files)

print(r)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM