function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
motti10motti10 

How do I call External REST services from APEX

My Product has REST base webservices have data from different sources.

 

How can I code APEX to return results based on calling my REST services and returning the data and then show it in VisualSource?

 

Thanks

VJSFDCVJSFDC

hi,

 

Please check the below link.Where recently for Winter 12 release Salesforce has provided some input on how to access Rest Web Service.

 

 

http://www.salesforce.com/us/developer/docs/apexcode/index.htm

 

Hope it helps.

 

Thanks.

motti10motti10

Thanks..

 

I may be missing something, but i am trying to post to this example URL


'http://]URL]/services/v1/rest/Scripto/execute/HelloWorld?username=[user]&password=V[pwd]&foo=hello')

 

It will return "hello"

 

Here is my "Groovy code that works)

 

 import org.apache.commons.httpclient.Credentials
 import org.apache.commons.httpclient.HostConfiguration
 import org.apache.commons.httpclient.HttpClient
 import org.apache.commons.httpclient.UsernamePasswordCredentials
 import org.apache.commons.httpclient.auth.AuthScope
 import org.apache.commons.httpclient.methods.GetMethod
 import org.apache.commons.httpclient.methods.PostMethod
 import org.apache.commons.httpclient.NameValuePair
 
 
 public static String httpGet(String urlStr) throws IOException {
  URL url = new URL(urlStr);
  HttpURLConnection conn =
      (HttpURLConnection) url.openConnection();

  if (conn.getResponseCode() != 200) {
    throw new IOException(conn.getResponseMessage());
  }

  // Buffer the result into a string
  BufferedReader rd = new BufferedReader(
      new InputStreamReader(conn.getInputStream()));
  StringBuilder sb = new StringBuilder();
  String line;
  while ((line = rd.readLine()) != null) {
    sb.append(line);
  }
  rd.close();

  conn.disconnect();
  return sb.toString();
}

httpGet ('http://]URL]/services/v1/rest/Scripto/execute/HelloWorld?username=[user]&password=V[pwd]&foo=hello')

 

Can I implement this same thing?

 

J&AJ&A

There was a Google Maps project written by Ron Hess that has an example of calling an external web service:

http://code.google.com/p/force-google-earth/source/browse/trunk/GoogleEarth/src#src%2Fclasses

 

What you are after is on the geocode function under the GoogleGeoCode class. Here is a snippet of that function:

public static xmldom geocode( string addr ) { 
    HttpRequest req = new HttpRequest();   
    string url = GoogleGeoCode.serviceUrl + '&output=xml&q=' + EncodingUtil.urlEncode(addr,'UTF-8');
    system.debug ( 'url is ' +url );
    req.setEndpoint( url );
    req.setMethod('GET');
        
    xmldom dom = null;
    try {
        Http http = new Http();
        HttpResponse response = http.send(req);    
        if (response.getStatusCode() != 200 ) {
            dumpResponse ( response);
        } else {
            dom = new xmldom( response.getBody() );
        } 
    } catch( System.Exception e) {
        System.debug('ERROR: '+ e);
    }  
    
    if ( googleGeoCode.debug > 0 && dom != null ) { 
        dom.dumpAll(); 
    } 
    return dom;
}

 

 

Hope this helps.

Ajay_SFDCAjay_SFDC
Hi there , 

You can use in the following way : 

public static Http objhttp;
    public static HttpRequest req ;
    public static HttpResponse res ;
public static void MakeRestCallout()
    {
           objhttp = new Http();
           req = new HttpRequest();
           res = new HttpResponse();
           req.setMethod('POST'); // req.setMethod('GET');
           req.setEndpoint('Set your endpoint');
           Blob headerValue = Blob.valueOf(UserName+ ':' + Password);
            String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);
          // Set the necessary Headers
           req.setHeader('Authorization', authorizationHeader);
            req.setHeader('Accept','application/vnd.cpc.authreturn+xml');
            req.setHeader('Content-type','application/vnd.cpc.authreturn+xml; charset=UTF-8');
            req.setHeader('Accept-Language', 'en-CA');
            req.setTimeout(120000);
  
   //Set request format
   String reqBody = '<XML> </XML>'
            req.setBody(reqBody);
  
   
            try {
                res = objhttp.send(req);
            }
            catch(System.CalloutException e) {
                System.debug('Callout error: '+ e);
               
            }
   if(res.getStatus().equalsIgnoreCase('OK') && res.getStatusCode() == 200)
            {
               // Logic to parse the response
              }
  
}

Thanks ,
 Ajay 
nitin sharmanitin sharma

What Ajay_SFDC has explained is the right way to do it.
 
I would say instead of Using  xml to communicate with the service,Try to do in Json format and set the parameters which you want to send in the body of the request and then parse the resposne.Sales force guide has got lot of information on this.

nitin sharmanitin sharma

Hi,
You can do something similar and below given code has worked in the past and this code will tell you how to send data in Json format


public void runApi(){
        String responseFromNet;
        System.debug('The other one is before the select statement');
        List<User> UserVal = [SELECT Email,firstname,lastname, username FROM User WHERE Id =: UserInfo.getUserId()];
       
         string endpointURL ='xxxxxxxxxxx'';
         
                
        
       
        HttpRequest reqData = new HttpRequest();
        Http http = new Http();
            
        reqData.setHeader('Content-Type','application/json');
        reqData.setHeader('Connection','keep-alive');
        reqData.setHeader('Content-Length','0');
        reqData.setTimeout(20000); 
        //reqData.setTimeout(90000); 
        reqData.setEndpoint(endpointURL);
        reqData.setBody('{"emailAddress":"'+userVal[0].email+'","firstName":"'+userVal[0].FirstName+'","lastName":"'+userVal[0].LastName}');
        reqData.setMethod('POST');
        
          try {
    
            HTTPResponse res = http.send(reqData);
            responseFromNet = res.getBody();
            
                       
            JSONObject jSon=new JSONObject('{"aa":'+responseFromNet+' }'); 
            
     
           
             }catch(Exception exp){
                    System.debug('exception '+exp);
                    //return null;
              }
    
            
             
            
             
            
    }