How to add POST Body data to Net.HttpRequest

Primary tabs

Hi, how do I add the POST body content to my Net.HttpRequest (It's not a key value pair, I am posting my own JSON to the remote server because it needs JSON in the body):

                set httpRequest=##class(%Net.HttpRequest).%New()

                set httpRequest.Https=1
                set httpRequest.Server="redacted.azurewebsites.net"
                set AbsolutePath="/api/redacted"
                set QueryString="?operation=redacted&id=redacted"
                 set status=httpRequest.Post(AbsolutePath_QueryString)
 
But how to add the Body to the request?
 
For the sake of this post, the body could be:
 
{ "MyKey":"MyValue" }
 
but in reality it's a highly nested, valid, JSON string.
 
 
Kind regards!
 

Replies

This should be something like:

do httpRequest.EntityBody.Clear()

do httpRequest.EntityBody.Write("Your Data")

set status=do httpRequest.Post(...)

Thanks so much!!! Especially for answering so quickly! Marked as accepted answer!

Hi Anthony,

Look at the doc for the property EntityBody, you can do something like :

Set body = { "MyKey":"MyValue" }
Do httpRequest.EntityBody.Write(  body.%ToJSON() )

 property EntityBody as %GlobalBinaryStream;

When an Entity-Body is included with a message, the data type of that body is determined via the header fields Content-Type and Content- Encoding. These define a two-layer, ordered encoding model.

This is a stream so to insert into this stream use:

	Do oref.EntityBody.Write("Data into stream")

Thanks! And for replying so quickly! Marked as accepted answer in addition to the previous comment, both are helpful!

Hi

Here is an example of a HTTP Operation POSTing HL7 messages. this HTTP request uses HTTPS and a Proxy Server. The lines I have highlighted in Yellow will be different in your case as you are sending JSON. Not clear if you are using FHIR. However your ContentType will most likely be application/json or application/json+fhir

    set tSC=$$$OK,pResponse=""
    try {
        set message=pRequest.OutputToString(,,.tSC) if 'tSC quit
        set tResponse = ##class(%Net.HttpResponse).%New(),tResponse.ContentType="application/hl7-v2"
        if '$IsObject(..HTTPRequest) {
            set pHttpRequest=##class(%Net.HttpRequest).%New()
            set pHttpRequest.Server=..Adapter.HTTPServer
            set pHttpRequest.Port=..Adapter.HTTPPort
            set pHttpRequest.ProxyServer=..Adapter.ProxyServer
            set pHttpRequest.ProxyPort=..Adapter.ProxyPort
            set pHttpRequest.ProxyTunnel=..Adapter.ProxyHttpTunnel
            set pHttpRequest.ProxyHTTPS=1
            set pHttpRequest.SSLConfiguration=..Adapter.SSLConfig
            set pHttpRequest.UserAgent="curl/7.29.0"
            set pHttpRequest.ContentEncoding="HL7-ER7"
            set pHttpRequest.ContentCharset="UTF-8"
            set pHttpRequest.ContentType="application/hl7-v2"
            set pHttpRequest.AcceptGzip=0
            set pHttpRequest.WriteRawMode=0
            set pHttpRequest.ReadRawMode=0
            set pHttpRequest.OpenTimeout=..Adapter.ConnectTimeout
            set pHttpRequest.Timeout=..Adapter.ResponseTimeout
            set pHttpRequest.WriteTimeout=..Adapter.WriteTimeout
            set pHttpRequest.SocketTimeout=115
            set ..HTTPRequest=pHttpRequest
        }
        set ..HTTPRequest.HttpResponse=tResponse
        do ..HTTPRequest.EntityBody.Write(message)
        set tSC=..HTTPRequest.Post(..Adapter.URL,0,1) if 'tSC {
            set sc=$$$DebugLog("HTTP Write","Error: "_$$$GetErrorText(tSC))
        }
        else {do $$$DebugLog("HTTP Write","Post Sucessful)}
        set response=..HTTPRequest.HttpResponse
        $$$TRACE("HTTP Response Status: "_response.StatusCode)
        if response.StatusCode=200 {
            if $IsObject(response.Data) {
                set message="" while 'response.Data.AtEnd {set message=message_response.Data.Read(,.tSC) if 'tSC quit}
                set pResponse=##class(EnsLib.HL7.Message).ImportFromString(message,.tSC) if 'tSC $$$TRACE("An error occurred creating Respnse Message: "_$system.Status.GetErrorText(tSC))
            }
        }
        else {
            set message="" if $IsObject(response.Data) {set message="" while 'response.Data.AtEnd {set message=message_response.Data.Read(,.tSC) if 'tSC quit}}
            set tSC=$$$ERROR(5001,"HTTP Response Status is "_response.StatusCode_" with Error Text: "_response.ReasonPhrase_" with Content: "_message) quit
        }
    }
    catch ex {
        set tSC=ex.AsStatus()
    }
    if 'tSC,'$IsObject(pResponse) {

  // Here I create a NACK HL7 message if I didn't get a valid response from the remote server. Possibly because the server is down or the 

 //server has crashed. I have a DTL that takes the inbound HL7 request message and transforms it into an HL7 ACK message. I force the ACK 

// Code to "AE" and use the contents of tSC (error status) as the Error Message. Note I make use of the 3rd parameter in the Transform()

// method that allows you to pass in an object containing any properties you want. This is a useful way of getting data into the DTL that

// doesn't exist in either your sourse or target objects.

        set pResponse=##class(EnsLib.HL7.Message).%New(),aux=##class(HPRS.Transformations.CreateNACKDTL.AUX).%New()
        set aux.ACKCode="AE",aux.ACKMessage=$system.Status.GetErrorText(tSC)
        set sc=##class(HPRS.Transformations.CreateNACKDTL).Transform(pRequest,.pResponse,.aux) if 'sc $$$TRACE("Unable to Create NACK Response HL7 Message")
    }
    $$$TRACE("Outcome of HTTP Operation: "_$s(tSC:"Ok",1:"Error: "_$$$GetErrorText(tSC)))
    quit $$$OK

Yours

Nigel Salm
 

Oh this is fabulous Nigel, thank you! In particular, the error routines are very helpful!

I've come across from C# and am still getting used to the scripting syntax here, all three of these answers have helped, we're properly posting now!

Kind regards,

Anthony Harrison

Hi Anthony

That's great.

If you have other questions relating to Adapters and all things Ensemble then Post them in the Dev Community and I'll keep an eye out for them.

Yours

Nigel