Monday, 22 August 2022

Integration Host HTTP sender as code

 The HTTP Sender in HL7 Soup's Integration Host is simple to use, but doesn't expose every possible feature of HTTP messaging.  I had to retrieve response headers, and these are not provided back in the UI.

Fortunately it uses c# in the code activity, so I was able to add the following code to save the day.


 //The following code is just a indication for getting started for an Activity. Edit or delete as you wish. Use the variable workflowInstance and activityInstance to access the running states of the workflow.

using System.Net;
using System.IO;

Encoding encoding = Encoding.UTF8;
               
using (WebClient client = new WebClient())
{
    client.UseDefaultCredentials = true;
    
    client.Headers.Add("Content-Type","text/plain"); 
    
    //Add all the headers that you want.
    // client.Headers.Add("yourHeaderName", workflowInstance.GetVariable("yourVariableName"));
    
    
    byte[] data = null;
       
    //Payload for posts if you need it.
    //var payload = "";
    //if (posting the message)
    //{
    //   payload =activityInstance.Message.Text;
    //    if (payload != null)
    //     {
    //        data = encoding.GetBytes(payload);
    //    }
    //     else
    //     {
    //         data = new byte[] { };
    //     }
    // }
    
    //credentials
    client.Credentials = new NetworkCredential("","");
    
    
    
    //Get the method as a string.
    string method = "GET";
    
    string url = HTTP://url.com";
    
    //Call HTTP Service
    string result = "";
    if (method == "GET")
    {
        //Get cannot pass a payload
        using (Stream stream = client.OpenRead(url))
        {
                 using (var streamReader = new StreamReader(stream))
                {
                    result = streamReader.ReadToEnd();
                }
         }
    }
    else
    {
        //Post, Put and Delete pass a payload.
        var bytes = client.UploadData(url, method, data);
        result = encoding.GetString(bytes);
    }
    
    if ( client.ResponseHeaders!=null)
    {
        foreach (var responseHeader in client.ResponseHeaders)
        {
            //process your response headers
            //e.g.
            workflowInstance.SetVariable("MyVariable", responseHeader.ToString());
        }
    }
    
}