HTTP Callout with XML Parcing

Example 1:

goto -> administration setup -> security controls -> remote site settings.
and add
Remote Site URL : http://maps.googleapis.com

Controller Class for HTTP Callout and Parcing
  1. public with sharing class XMLPraseClass {

  2.     public String textToParse{ get; set; }
  3. //clickme() is for HTTP Callout - in response it will get a XML file
  4. public void clickme()    {
  5.         String strurl='http://maps.googleapis.com/maps/api/geocode/xml?address=92618&sensor=false';
  6.         HttpRequest req=new HttpRequest();
  7.         req.setEndpoint(strurl);
  8.         req.setMethod('POST'); // req.setMethod('GET');
  9.         string strbody='hi';
  10.         req.setBody(strbody);
  11.         req.setCompressed(true);
  12.         Http http=new Http();
  13.         HTTPResponse res=http.send(req);
  14.         textToParse=res.getbody();
  15.       
  16.     }
  17.     
  18.      public String parsedText {get; set;}
  19.     
  20.     // The main method for parcing the XML response received by the http callout
  21.     public PageReference parse() {
  22.        if (textToParse== null) {
  23.          parsedText = 'Nothing to parse';
  24.        } else {
  25.          parsedText = parse(textToParse);
  26.        }
  27.         return null;
  28.     }
  29.     
  30.     // Just checking that it's actually XML
  31.     private String parse(String toParse) {
  32.       DOM.Document doc = new DOM.Document();
  33.       
  34.       try {
  35.         doc.load(toParse);    
  36.         DOM.XMLNode root = doc.getRootElement();
  37.         return walkThrough(root);
  38.         
  39.       } catch (System.XMLException e) {  // invalid XML
  40.         return e.getMessage();
  41.       }
  42.     }

  43.     // Recursively walk through the XML
  44.     private String walkThrough(DOM.XMLNode node) {
  45.       String result = '\n';
  46.       if (node.getNodeType() == DOM.XMLNodeType.COMMENT) {
  47.         return 'Comment (' +  node.getText() + ')';
  48.       }
  49.       if (node.getNodeType() == DOM.XMLNodeType.TEXT) {
  50.         return 'Text (' + node.getText() + ')';
  51.       }
  52.       if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
  53.         result += 'Element: ' + node.getName();
  54.         if (node.getText().trim() != '') {
  55.           result += ', text=' + node.getText().trim();
  56.         }
  57.         if (node.getAttributeCount() > 0) { 
  58.           for (Integer i = 0; i< node.getAttributeCount(); i++ ) {
  59.             result += ', attribute #' + i + ':' + node.getAttributeKeyAt(i) + '=' + node.getAttributeValue(node.getAttributeKeyAt(i), node.getAttributeKeyNsAt(i));
  60.           }  
  61.         }
  62.         for (Dom.XMLNode child: node.getChildElements()) {
  63.           result += walkThrough(child);
  64.         }
  65.         return result;
  66.       }
  67.       return '';  //should never reach here
  68.       
  69.     }
  70.  }

Page:
<apex:page showHeader="false" controller="XMLPraseClass" >
<apex:form >
<apex:pageBlock >
<apex:pageblockSection >
<apex:commandButton value="Click Me" action="{!clickme}" reRender="result1"/>
</apex:pageblockSection>
</apex:pageBlock>
<apex:outputPanel id="result1">
     <apex:inputtextarea cols="40" rows="20" value="{!textToParse}"  />
     <apex:inputtextarea cols="40" rows="20" id="result" value="{!parsedText}"/>    
     <br />
     <apex:commandButton value="Parse" action="{!parse}" reRender="result"/>
</apex:outputPanel>

</apex:form>

</apex:page>


Example 2:
step1:

Add the end point url in remote site settings.

url:
----
http://maps.googleapis.com/maps/api/geocode/xml?address=92618&sensor=false

goto -> administration setup -> security controls -> remote site settings.

step2:


write the below class:
========================

public with sharing class HttpClass {
    public void clickme()
    {
        String strurl='http://maps.googleapis.com/maps/api/geocode/xml?address=92618&sensor=false';
        HttpRequest req=new HttpRequest();
        req.setEndpoint(strurl);
        req.setMethod('POST'); // req.setMethod('GET');
        string strbody='hi';
        req.setBody(strbody);
        req.setCompressed(true);
        Http http=new Http();
        HTTPResponse res=http.send(req);
        string strRes=res.getbody();
        system.debug('**** XML Data is *****'+strRes);

// Parse either XML / JSON  Response  using those methods (JSON / XML Parse Methods)
    }
}



step3:
======

call the above class from the developer console.


Developer console code:
------------------------

HttpClass objH = new HttpClass ();
objH.clickme();

================


xml parsing:

                                                       
                                           
Page:

<apex:page controller="XMLParseClass">
 <apex:form >
     <apex:pageblock >
         <apex:pageblocksection >
                <apex:inputfile value="{!objD.body}" filename="{!objD.name}"></apex:inputfile>
                <apex:commandButton value="Parse" action="{!doParse}"/>
         </apex:pageblocksection>
     </apex:pageblock>
 </apex:form>
</apex:page>


class:

public with sharing class XMLParseClass {

    public Document objD { get; set; }

    public XMLParseClass(){
         objD = new Document();
    }
 
 
    public void doParse(){
       String xml = objD.body.toString();
       Dom.Document doc = new Dom.Document();
        doc.load(xml);
        XMLTest__c objxml;
        List<XMLTest__c> lstX = new List<XMLTest__c>();
     
        lstX = new List<XMLTest__c>();
        for(DOM.XMLNode rootnode : doc.getRootElement().getChildElements()){
         
            objxml = new XMLTest__c();
             Integer i=0;
            for(DOM.XMLNode dept: rootnode.getChildElements()){
                    if(i==0){
                        objxml.Name = dept.getText();
                            system.debug('---objxml.name is --->'+objxml.Name);
                        }
                    if(i==1){
                        objxml.street1__c = dept.getText();
                        }
                    if(i==2){
                        objxml.street2__c = dept.getText();
                        }
                    if(i==3){
                        objxml.city__c = dept.getText();
                        }
                    if(i==4){
                        objxml.state__c = dept.getText();
                        }
                    if(i==5){
                        objxml.country__c = dept.getText();
                        }
                     i++;
            }
           
             lstX.add(objxml);
        }
        system.debug('--lstX is -->'+lstX);
        insert lstX;
     
     
    }

}



sample xml:

                             
<company>
  <department>
    <name>Sachin</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
  </department>
  <department>
    <name>Sourav</name>
    <street1>Culcutta St</street1>
    <street2>Apt. 2</street2>
    <city>Culcutta</city>
    <state>XYZ</state>
    <country>India</country>
  </department>
</company>

Comments

Popular Posts