Problem adding JSON content to WinHttpRequest POST request in classic ASP

扶醉桌前 提交于 2020-04-16 02:49:09

问题


I am trying to retrieve data using an NHS API and the instructions are as follows...

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
}

Following the answer here How can I post data using cURL in asp classic? I tried this...

<%
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
%>

...but this gives me "Server returned: 400 Bad Request". It's almost certainly a case of me not knowing how to do this properly. Where am I going wrong? Thanks


回答1:


The issue is the API expects an application/json body, so you need to pass that instead of application/x-www-form-urlencoded data.

You can build the JSON up as a string but it needs to conform to a JSON structure or you will likely get an HTTP 400 Bad Request again.

Replace data with;

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

You could also use some existing libraries to build and parse JSON for you.

Personally I'd recommend - JSON object class by RCDMK



来源:https://stackoverflow.com/questions/61057258/problem-adding-json-content-to-winhttprequest-post-request-in-classic-asp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!