Question
· Sep 27

Send JSON with HTTP post

Hi Guys,

How can I send JSON with HTTP post request?

Thanks

Product version: Ensemble 2018.1
Discussion (3)3
Log in or sign up to continue

Something like this operation should do it for you.

 

Class Component.Outbound.JsonHttpsOut Extends Ens.BusinessOperation
{

Parameter ADAPTER = "EnsLib.HTTP.OutboundAdapter";

Property Adapter As EnsLib.HTTP.OutboundAdapter;

Method SendMessage(pMsgOut As %DynamicObject, Output pMsgIn As %Net.HttpResponse) As %Status
{
    S tSC=$$$OK
    Set tHttpRequest=##class(%Net.HttpRequest).%New(), tHttpRequest.WriteRawMode=1, token =##class(%DynamicObject).%New(), tSC=$$$OK
    Set tHttpRequest.SSLConfiguration=..Adapter.SSLConfig
    Set tSC = tHttpRequest.SetHeader("Content-Type", ..ContentType)
    d tHttpRequest.EntityBody.Write(pMsgOut.%ToJSON())
    #dim tHttpResponse As %Net.HttpResponse
    Set tHttpResponse = ##class(%Net.HttpResponse).%New()
    S send="POST"
    Set tSC=..Adapter.SendFormDataArray(.tHttpResponse, send, tHttpRequest)
    if (tHttpResponse.StatusCode="200"){
        set message=tHttpResponse.StatusCode_": "_tHttpResponse.StatusLine_". "
        if $IsObject(tHttpResponse.Data) 
        {
               while 'tHttpResponse.Data.AtEnd {
                   set message=message_tHttpResponse.Data.Read(,.tSC1) 
                   if 'tSC1 quit
            }
            $$$TRACE(message)
            s tSC=$$$ERROR("9999",message)
        }
        s tSC=$$$OK
        }
    else
    {
        set message=tHttpResponse.StatusCode_": "_tHttpResponse.StatusLine_". "
        if $IsObject(tHttpResponse.Data) 
        {
               //set message="" 
               while 'tHttpResponse.Data.AtEnd {
                   set message=message_tHttpResponse.Data.Read(,.tSC1) 
                   if 'tSC1 quit
            }
            $$$TRACE(message)
            s tSC=$$$ERROR("9999",message)
        }
        Set ..Adapter.URL=$REPLACE(..Adapter.URL,..tmpurl,"")    //sets adapter url back to standard if it was last used to remove an MRN
    }

    Q tSC
}

To send JSON with an HTTP POST request using InterSystems ObjectScript, you can use the %Net.HttpRequest class. Here is a sample code snippet demonstrating how to do this:

Create an HTTP request object.
Set the server URL and other necessary properties.
Write the JSON payload to the request’s entity body.
Send the POST request.

Here is an example:

Set Body={}
Set Body.Name="John Smith"
Set Body.Address="ISC Dev community"
Set Body.SomeProperty="Some content"
Set Request = ##class(%Net.HttpRequest).%New()
Set Request.Server = "server"
Set Request.Location = "location"
Set Request.ContentType = "application/json"
// Convert the object to JSON and write it to the request's entity body
Do Body.%ToJSON(Request.EntityBody)

// Send the POST request
Set Status = Request.Post()