Monday 30 March 2015

Calling external WebService & parsing its XML Response using Salesforce's Apex

In this Tip, "http://xml.utrace.de/?query=" is used as external web service , which takes global IP as its request parameter (e.g http://xml.utrace.de/?query=111.93.167.67). Then it returns XML data as its response .
The format of XML response for above example is as follows
<?xml version="1.0" encoding="iso-8859-1" ?>
<results>
<result>
  <ip>111.93.167.67</ip>
  <host />
  <isp>Tata Teleservices ISP</isp>
  <org>Tata Teleservices ISP</org>
  <region>Calcutta</region>
  <countrycode>IN</countrycode>
  <latitude>22.569700241089</latitude>
  <longitude>88.369697570801</longitude>
  <queries>2</queries>
  </result>
  </results>

Apex Class

public class OrgInfo_XmlStreamReader {

public String org{get;set;}
public List<String> XMLData{get;set;}

public OrgInfo_XmlStreamReader(){
XMLData=new List<String>();

}

public List<String> getOrganisationInfo(String ip){ 
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('http://xml.utrace.de/?query='+ip);
req.setMethod('GET');
HttpResponse res = http.send(req);

// Log the XML content
String xmlContent=res.getBody();
System.debug(res.getBody());
System.debug('#####XmlStreamReader ##11##');
// Generate the HTTP response as an XML stream

XmlStreamReader reader = res.getXmlStreamReader();
System.debug('##########XML DATA##########'+res.getXmlStreamReader());

XMLData=XMLParser(res.getBody());
return XMLData;
}

public List<String> XMLParser(String strXml){
System.debug('####Inside XMLParser Method########'+strXml);
List<String> orgInfo=new List<String>();
Dom.Document doc = new Dom.Document();
doc.load(strXml);
//Retrieve the root element for this document.
Dom.XMLNode Envelope = doc.getRootElement();
Dom.XMLNode Body= Envelope.getChildElements()[0];
string user_createResult = '';

for(Dom.XMLNode child : Body.getChildElements()) {
orgInfo.add(child .getText());
}
return orgInfo;
}

}

 Call the method getOrganisationInfo(String ip) from the Class , where you need the parsed data.
This method will return a String List containingIP,HOST,ISP,ORGANISATION NAME,REGION,COUNTRY CODE,LATITUDE,LONGITUDE, and NUMBER OF QUERIES from YOU . This information is in sequential manner inside the List(index 0,1,....n).

Note: Before Calling a external/remote site, please registered that site under
SetUP-->Security Control--> Remote Site Setting

References:- http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_classes_xml_XmlStream_reader.htm