Skip to main content
Hi Everyone,

Could anyone explain me that how to make Http callouts in batch class with example.

Note:Need to call the batch class from apex trigger
8 respostas
  1. 30 de jun. de 2017, 12:52
    Hi try this,

     

    global class BatchSync implements Database.Batchable<sObject>, Database.AllowsCallouts {

    public String query = 'Select ID, Name from Account';

    global Database.QueryLocator start(Database.BatchableContext BC) {

    return Database.getQueryLocator(query);

    }

    global void execute(Database.BatchableContext BC, List<Account> records) {

    String endpoint;

    for ( integer i = 0; i< records.size(); i++ ){

    try {

    HttpRequest req = new HttpRequest();

    HttpResponse res = new HttpResponse();

    Http http = new Http();

    // Set values to Params

    endpoint = 'Your endpoint';

    req.setHeader('Authorization', header);

    req.setHeader('Content-Type', 'application/json');

    req.setEndpoint(endpoint);

    req.setMethod('POST');

    req.setBody('Information you wanna send');

    req.setCompressed(true); // This is imp according to SF, but please check if

    // the webservice accepts the info. Mine did not :P

    // Had to set it to false

    if (!Test.isRunningTest()) {

    res = http.send(req);

    String sJson = res.getBody();

    System.debug('Str:' + res.getBody());

    }

    // now do what u want to with response.

    }

    catch (Exception e) {

    System.debug('Error:' + e.getMessage() + 'LN:' + e.getLineNumber() );

    }

    }

    }

    global void finish(Database.BatchableContext BC){

    }

    }

    BatchSync BS = new BatchSync();

    Database.executeBatch(BS,10); // you can also do less than 10

    You can also take  help from these   link

    1-https://developer.salesforce.com/forums/?id=906F0000000kK6VIAU

    2-http://www.forcedisturbances.com/2012/03/caching-data-from-googles-geocoding.html

    I Hope you will choose my answer as best answer