Use the Continuation class to make callouts asynchronously to a SOAP or REST Web service.
Visualforce page:
<apex:page controller="ContinuationController">
<apex:pageMessage rendered="{!statusBool}" severity="Info" summary="Long running process. So, do not press Start Request multiple times."/>
<apex:form >
<apex:commandButton action="{!startRequest}"
value="Start Request" reRender="result"/>
</apex:form>
<apex:outputText id="result" value="{!result}" />
</apex:page>
Apex Class:
public with sharing class ContinuationController {
public String requestLabel;
public String result {get;set;}
private static final String LONG_RUNNING_SERVICE_URL = 'https://api.github.com/users/hadley/orgs';
public Boolean statusBool {get;set;}
public ContinuationController() {
statusBool = false;
}
// Action method
public Object startRequest() {
statusBool = true;
Continuation con = new Continuation(40);
// Set callback method
con.continuationMethod='processResponse';
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(LONG_RUNNING_SERVICE_URL);
this.requestLabel = con.addHttpRequest(req);
return con;
}
// Callback method
public Object processResponse() {
statusBool = false;
HttpResponse response = Continuation.getResponse(this.requestLabel);
this.result = response.getBody();
return null;
}
}
When the user hits Start Request button, the callout is made to the URL. Once the response is sent, processResponse method will be called. statusBool variable will be true when the request is hit and it shows the message. Once we get the response, statusBool will be false and hide the message.