在经典 ASP 中向 WinHttpRequest POST 请求添加 JSON 内容时出现问题

Problem adding JSON content to WinHttpRequest POST request in classic ASP

我正在尝试使用 NHS API 检索数据,说明如下...

Endpoint        https://api.nhs.uk/service-search/search?api-version=1
Method      POST
Headers     Content-Type: application/json
subscription-key: MYKEYHERE
Body        {
    "filter": "OrganisationTypeID eq 'PHA'",
    "orderby": "OrganisationName",
    "top": 25,
    "skip": 0,
    "count": true
}

按照这里的回答我试过了...

<%
Dim http: Set http = Server.CreateObject("WinHttp.WinHttpRequest.5.1")
StrFilter = "OrganisationTypeID eq 'PHA'"
StrFilter = Server.UrlEncode(StrFilter)
Dim url: url = "https://api.nhs.uk/service-search/search?api-version=1"
Dim data: data = "filter=" & StrFilter & "&orderby=OrganisationName&top=25&skip=0&count=true"
With http
  Call .Open("POST", url, False)
  Call .SetRequestHeader("subscription-key", "MYKEYHERE")
  Call .SetRequestHeader("Content-Type", "application/json")
  Call .Send(data)
End With
If Left(http.Status, 1) = 2 Then
  'Request succeeded with a HTTP 2xx response, do something...
  Response.Write http.responseText
Else
  'Output error
  Call Response.Write("Server returned: " & http.Status & " " & http.StatusText)
End If
%>

...但这给了我 "Server returned: 400 Bad Request"。几乎可以肯定的是,我不知道如何正确地做到这一点。我哪里错了?谢谢

问题是 API 需要 application/json 正文,因此您需要传递它而不是 application/x-www-form-urlencoded 数据。

您可以构建 JSON up as a string,但它需要符合 JSON 结构,否则您可能会再次获得 HTTP 400 Bad Request

data替换为;

Dim data: data = "{ ""filter"": ""OrganisationTypeID eq 'PHA'"", ""orderby"": ""OrganisationName"", ""top"": 25, ""skip"": 0, ""count"": true }"

您也可以 为您构建和解析 JSON。

我个人推荐 - JSON object class by RCDMK

我解决了这个问题

url="https://test/xyzapi/api/Account/login"
Dim oXMLHttp
dim auth_token
Set oXMLHttp=Server.Createobject("MSXML2.ServerXMLHTTP.6.0")
oXMLHttp.setOption 2, 13056
oXMLHttp.open "POST", url,false
oXMLHttp.setRequestHeader "Content-Type","application/json"
oXMLHttp.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; 
Windows NT 5.0)"
strJSONToSend ="{""Username"":""test"",""Password"":""123456""}"