Excel VBA中HTTP POST出现400错误“无效的请求体”

zpqajqem  于 2023-03-31  发布在  其他
关注(0)|答案(1)|浏览(539)

我的任务是在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父/子参数应该如何格式化?

hwamh0ep

hwamh0ep1#

Dim data
   ' some test data
   data = Array(, 1, "A", 2, "B", "C", "D")
   
   Dim sAllParams As String
   sAllParams = "{'MyParamName1':" & data(1) & _
    ",'MyParamName2': '" & data(2) & _
    "','MyParamName3': " & data(3) & _
    ",'MyParaName4': '" & data(4) & _
    "','MyParamParentName': {" & _
    "'MyParamChildName1':'" & data(5) & _
    "','MyParamChildName2':'" & data(6) & _
    "'}}"
    sAllParams = Replace(sAllParams, "'", """")
    
    Debug.Print sAllParams

    httpRequest.send sAllParams

相关问题