我的任务是在Excel VBA中执行HTTP POST,我有一个HTTP GET在相同的上下文中工作正常。
首先,这里是在此上下文中正常工作的HTTP GET,名称一般化:
Set httpRequest = CreateObject("MSXML2.XMLHTTP")
MyApiUrl = "https://MyServer/MyFolder/MySearchAPI?MyParamName1=MyParamValue1&MyParamName2=MyParamValue2"
httpRequest.Open "GET", MyApiUrl, False
httpRequest.setRequestHeader "Content-Type", "application/json"
httpRequest.setRequestHeader "my-api-key", "my api key value"
httpRequest.send
以下是我被告知让这个HTTP POST工作的所有内容:
首先,API名称为MyUpdateAPI,URL路径相同:https://MyServer/MyFolder/MyUpdateAPI
其次,参数(XLM格式?)如下所示,名称也是通用的:
{
"MyParamName1": MyParamValue1,
"MyParamName2": "MyParamValue2",
"MyParamName3": MyParamValue3,
"MyParamName4": "MyParamValue4",
"MyParamParentName": {
"MyParamChildName1": "MyParamChildValue1",
"MyParamChildName2": "MyParamChildValue2"
}
}
一些同事有一个测试工具,他们将XML粘贴到其中,它返回200,成功。
我不知道如何将XML父/子参数转换成HTTP参数。
以https://codingislove.com/http-requests-excel-vba/的Excel VBA中的示例HTTP POST为指导,我尝试了以下操作:
'build params:
MyParam1 = "MyParamName1=MyParamValue1" '(no ampersand on the first param).
MyParam2 = "&MyParamName2=MyParamValue2"
MyParam3 = "&MyParamName3=MyParamValue3"
MyParam4 = "&MyParamName4=MyParamValue4"
MyParamChild1 = "&MyParamChildName1=MyParamChildName1"
MyParamChild2 = "&MyParamChildName2=MyParamChildName2"
sAllParams = MyParam1 & MyParam2 & MyParam3 & MyParam4 & MyParamChild1 & MyParamChild2
Set httpRequest = CreateObject("MSXML2.XMLHTTP")
MyApiUrl = "https://MyServer/MyFolder/MyUpdateAPI"
httpRequest.Open "POST", MyApiUrl, False
httpRequest.setRequestHeader "Content-Type", "application/json"
httpRequest.setRequestHeader "my-api-key", "my api key value"
httpRequest.send sAllParams
有谁能告诉我我做错了什么吗?在HTTP参数字符串中,XML父/子参数应该如何格式化?
1条答案
按热度按时间hwamh0ep1#