Tuesday, July 15, 2014

How to add SOAP header to a Salesforce call out

There are situations when we need to add a SOAP header to the call out being made. If your WSDL has a definition for a SOAP header then the Apex to WSDL tool will generate the header code for you.

But most of the times the WSDL does not have the header information and the receiving server needs specific SOAP header to validate the call. In such a case we can add a custom header to the call. Here are the steps to add a customer.  e.g. If we need to send the following in the header.

<ApplicationContext>
    <consumerSystem>UN</consumerSystem>
    <organisation>PW</organisation>
</ApplicationContext>

1. Add a data structure to the stub generated for your data to be sent. For the example the class to be added to the stub would look like .
public class PolicyManagement_V2_Schema{ // this is the parent class which has the stub definition
public class ApplicationContext {
        public String consumerSystem;
        public String organisation;
        private String[] consumerSystem_type_info = new String[]{'consumerSystem','<SOAP Namespace>',null,'0','1','false'};
        private String[] organisation_type_info = new String[]{'organisation','<SOAP Namespace>',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'<SOAP Namespace>','true','false'};
        private String[] field_order_type_info = new String[]{'consumerSystem','organisation'};
    }
}
2. Add the following code to the class which makes the call out. Declare the application context as a local class variable and use <variable>_hns = '<PrimaryNode>=<SOAP Namespace>'. Adding the _hns node tells salesforce to put the information of the class in the SOAP header.
public PolicyManagement_V2_Schema.ApplicationContext Header;
private String Header_hns = 'ApplicationContext=http://www.iag.co.nz/soa/apexiaa/v2';

3. Once you have done step 1 and 2, you are all set to send custom data in SOAP header call out. All you need to do now is to instantiate the header variable in the actual call out and set the values for the class variables which would be sent as part of SOAP header.