Salesforce Certified Application Architect

Wednesday 22 January 2014

How to integrate SFDC with external webservice?


Salesforce: APEX HTTP callout example, POST and GET
Steps to implement apex HTTP callout:
How to integrate SFDC with external webservice?



Using this you can integrate your SFDC instance with external systems, that can be your SAP, Oracle Apps or any other in-house application which need your sfdc data more or less immediately to process request.

This callout is for Rest webservice:
 
1) External system enabled with REST webservice with JSON/XML response ( we are using Json in this example)
2) Register, our external endpoint URL with SFDC "Remote sites". ( endpoint URL, is the external system URL which will serving your request)

3) Invoking HTTP Callouts using following code:


Following is the sample/example apex class which is making callouts to external system rest webservice. This example also shows you , how Serializeand deSerialize Json. (Object to Json String and vise-verse).

public with sharing class TestHttpCallOut {

String endPoint = 'http://***yousite_app***.com/sfdc';

public void postDataToRemote(String name,String email,Integer age){
   performAction('POST',name,email,age);  
}
public void fetchDataFromRemote(){
   performAction('GET');  
}


 public void performAction(String method,String name,String email,Integer age){
           
             //Prepare http req
             HttpRequest req = new HttpRequest();
             req.setEndpoint(endPoint);
             req.setMethod(method);
           
                Map<String,object> mapEmp = new Map<String,object>();
                mapEmp.put('name',name);
                mapEmp.put('email',email);
                mapEmp.put('age',age);
                String JSONString = JSON.serialize(mapEmp);  
       
           
            req.setBody(JSONString);
           
            Http http = new Http();
            HTTPResponse res = http.send(req);
           
            System.debug(res.getBody());
       
  }
 
public void performAction(String method){

             HttpRequest req = new HttpRequest();
             req.setEndpoint(endPoint);
             req.setMethod(method);
           
            Http http = new Http();
            HTTPResponse res = http.send(req);
            Map<String,String> responseMap =   (Map<String,String>)JSON.deSerialize(res.getBody(),Map<String,String>.class);
             
              System.debug(responseMap);
             
  }
   
 
}

Use folloiwng commented code to execute this example,

/*
//TestHttpCallOut  a = new TestHttpCallOut ();
//a.fetchDataFromRemote();
//a.postDataToRemote('BOB','abc@xyz.com',101);
*/

No comments:

Post a Comment

Salesforce Certified Application Architect & Certified Data Architecture and Management Designer Exam

How to pass Salesforce Certified Data Architecture and Management Designer Exam This exam was 1st architect exam for me. Its not that muc...