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





  111.93.167.67

  

  Tata Teleservices ISP

  Tata Teleservices ISP

  Calcutta

  IN

  22.569700241089

  88.369697570801

  2

  

  

Apex Class

 

public class OrgInfo_XmlStreamReader {

 

public String org{get;set;}

public List XMLData{get;set;}

 

public OrgInfo_XmlStreamReader(){

XMLData=new List();

 

}

 

public List 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 XMLParser(String strXml){

System.debug('####Inside XMLParser Method########'+strXml);

List orgInfo=new List();

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

150 150 Burnignorance | Where Minds Meet And Sparks Fly!