Future Callout with apex trigger for a webservice
if(System.IsBatch() == false && System.isFuture() == false){
Error if this above condition is not used in trigger: System.AsyncException: Future method cannot be called from a future or batch method: herokuapp.animalname(String)
Animal__c is a string field to update a value of o index from the webservice call.
Trigger:
trigger herokuapp_account on Account (after update) {
for(account a: trigger.new)
{
if(System.IsBatch() == false && System.isFuture() == false){
if(trigger.isUpdate)
{
herokuapp.animalname(a.id);
}
}
}
}
Trigger Handler
public with sharing class herokuapp {
@future(callout=true)
public static void animalname(string id)
{
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
// Deserialize the JSON string into collections of primitive data types.
Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
// Cast the values in the 'animals' key as a list
List<Object> animals = (List<Object>) results.get('animals');
System.debug('Received the following animals:');
Account a=new Account();
integer i=0;
List<Account> aList=new List<Account>();
string animalname=animals[0].toString();
system.debug('animalname'+animalname);
a.id=id;
a.Animal__c=animalname;
system.debug(a);
update a;
}
}
}
Comments
Post a Comment