Check the below video first if you are planning to use Continuation
We may run into scenario in Salesforce project, where we need call external web service but no need to wait for response. Response from external web service can be processed asynchronously and once processed it can be presented in Visualforce page.
We can accomplish this by using Actionsupport or Javascript remoting. However, this is possible with using Continuation method as well. In Continuation approach, we can call external web service and inform that which callback method should be used to process response. After execution of callback method, data is presented in visualforce page.
Below code demonstrate complete usage of this.
Apex code
/** * @Author : Jitendra Zaa * @Web : https://jitendrazaa.com * * */ public class ISOtoCodeService { public String countryISO {get;set;} public String response {get;set;} private String baseSericeURL = 'http://services.groupkt.com/country/get/iso2code/'; private String returnedContinuationId ; public ISOtoCodeService() { countryISO = 'IN'; } public Object requestService(){ //Timeout in seconds, 60 is limit Continuation con = new Continuation(60); // Set callback method con.continuationMethod='renderResponse'; // Create callout request HttpRequest req = new HttpRequest(); req.setMethod('GET'); req.setEndpoint(baseSericeURL+countryISO); returnedContinuationId = con.addHttpRequest(req); return con; } public Object renderResponse() { // Get the response by using the unique label HttpResponse httpRes = Continuation.getResponse(returnedContinuationId); // Set the result variable that is displayed on the Visualforce page response = httpRes.getBody(); // Return null to re-render the original Visualforce page return null; } }
Visualforce code
<apex:page tabStyle="Opportunity" controller="ISOtoCodeService" docType="html-5.0" sidebar="false" showHeader="false" showChat="false"> <apex:form > <apex:pageBlock title="Continuation Demo"> Country ISO : <apex:input label="Country ISO" value="{!countryISO}"/> <apex:commandButton action="{!requestService}" value="Request Service" reRender="responseBlock"/> </apex:pageBlock> <apex:pageBlock title="Response from Webservice" id="responseBlock"> <pre> {!response} </pre> </apex:pageBlock> </apex:form> <style type="text/css"> pre{ font-size : 1.7em; } </style> </apex:page>
Make sure to add URL “http://services.groupkt.com” in remote site settings.
Live Demo :
Leave a Reply