How can I call the HTTP REST API and show the data at the page loading time? I developed the code which has button and that I need to hit each time to get the results, instead I want to have the that data at page loading time.
public class ApexRestController {
public List<CaseDetail> caseList {get; set;}
public static String getAccessToken(){
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setHeader('Content-Type','application/x-www-form-urlencoded');
req.setEndpoint('https://ap5.salesforce.com/services/oauth2/token');
String CLIENT_ID = 'xx';
String CLIENT_SECRET = 'xx';
String USERNAME = 'xx';
String PASSWORD = 'XX';
req.setBody('grant_type=password' + '&client_id='+CLIENT_ID +
'&client_secret='+CLIENT_SECRET + '&username='+USERNAME + '&password='+PASSWORD);
Http http = new Http();
HTTPResponse res = http.send(req);
return getAccessTokenValue(res.getBody());
}
public static String getAccessTokenValue(String jsonInput){
Map<String, Object> data = (Map<String, Object>) JSON.deserializeUntyped(jsonInput);
return (String) data.get('access_token');
}
public PageReference getCaseDetailsById(){
Http http = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://ap5.salesforce.com/services/apexrest/Cases/XXXXXXXX');
req.setMethod('GET');
req.setHeader('Authorization', 'Bearer '+getAccessToken());
HTTPResponse res = http.send(req);
String json = res.getBody();
CaseDetail ca = (CaseDetail) System.JSON.deserialize(json.replace('"type"','"type_Z"'), CaseDetail.class);
caseList = new List<CaseDetail>();
caseList.add(ca);
System.debug('Case Details : '+caseList);
return null;
}
}
CaseDetailsVFPage:
<apex:page controller="ApexRestController">
<apex:form >
<apex:pageBlock >
<apex:commandButton reRender="table1" value="Get Case Details" action="{!getCaseDetailsById}"/>
</apex:pageBlock>
<apex:pageBlock id="table1">
<b>Output Contact Details </b>
<apex:pageBlockTable value="{!caseList}" var="ca">
<apex:column headerValue="Id" value="{!ca.Id}" />
<apex:column headerValue="CaseNumber" value="{!ca.CaseNumber}" />
<apex:column headerValue="Subject" value="{!ca.Subject}" />
<apex:column headerValue="Status" value="{!ca.Status}" />
<apex:column headerValue="Priority" value="{!ca.Priority}" />
<apex:column headerValue="Type" value="{!ca.Attributes.type_Z}" />
<apex:column headerValue="URL" value="{!ca.Attributes.url}" />
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>