XML and HTTP != SOAP

In a real and timeless world, SOAP is a great option. But please, before going the SOAP way, think if there is a simpler protocol that suits your needs. 

Remind that Web was explosive even before the advent of Web services. If XML/JSON over HTTP can possibly solve a problem, or allows a dynamic structure that can rise your service functionalities, it’s well worth considering.

Apex allows you to programmatically send JSON and XML over HTTP with the HTTPRequest Apex class. In your career as a Salesforce developer you will likely have to use it, so below we’ll have a quick look at it.

As usual you have to authorise the destination endpoint. Open your organization and go to Setup > Security Controls  > Remote Site Settings. Then click on the “New Remote Site” button, and enter a Name/URL for the endpoint:

 

 

As an alternative, if you’re a real trailblazer you can use Named Credentials as Callout Endpoints.

Then create the Apex class that will send messages to the external service, using the proper Content-Type, endpoint and an XML string as the body.

Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndPoint(endpoint);
req.setHeader('Content-Type', 'text/xml; encoding="utf-8"');
req.setMethod('POST');
req.setBody('<?xml version="1.0" encoding="utf-8"?>'
   +'<note>'
     +'<to>Foo</to>'
     +'<from>Bar</from>'
     +'<heading>Reminder</heading>'
     +'<body>Remember to remember!</body>'
   +'</note>');
HttpResponse res = h.send(req);
res.getBody();

 

Et voilà! The endpoint will receive it as XML over HTTP, without the need of WSDL or complex descriptors to send/receive a small message.
For example:   

 

 

 

References:
– https://www.ibm.com/developerworks/library/x-tiphttp/index.html
– https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_httprequest.htm#apex_System_HttpRequest_constructors

Christian Tinghino

Senior Developer, 2x Salesforce certified

Leave a Reply

Your email address will not be published. Required fields are marked *