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

http://www.platforce.org/batch-apex.html

https://www.biswajeetsamal.com/blog/batch-apex-with-webservice-callout/

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

global Database.QueryLocator start(Database.BatchableContext BC)
{
string obj = 'ACA';
String query = 'Select Id, CreatedDate, CreatedBy.Name, Attest_ID__c from Case where Ticket_Type__c = :obj';
return Database.getQueryLocator(query);
} global void execute(Database.BatchableContext BC, List<Account> scope)
{
List<Voice_File_Loader__c> searchVFL = [Select Id, Call_Date_Time__c, End_Window__c, Agent_Name__c, Voice_File_Location__c from Voice_File_Loader__c]; for (Account checkCase : scope){ for (Voice_File_Loader__c matchVFL :searchVFL){
boolean after = (checkCase.CreatedDate >= matchVFL.Call_Date_Time__c);
boolean before = (checkCase.CreatedDate <= matchVFL.End_Window__c);
boolean timeCheck = (after && before);
boolean nameCheck = (checkCase.CreatedBy.Name.equalsIgnoreCase(matchVFL.Agent_Name__c));
if (timeCheck && nameCheck){
Attachment att = new Attachment();
Http binding = new Http();
HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint(matchVFL.Voice_File_Location__c);
HttpResponse res = binding.send(req);
Blob b = res.getbodyasblob();
att.name = 'Voice Attestation.wav';
att.body = b;
att.parentid = checkCase.Id;
system.debug('#############'+ att);
insert att;
delete matchVFL;
}
}
} }
global void finish(Database.BatchableContext BC)
{
}

  

batchAccountUpdate a = new batchAccountUpdate();
database.executebatch(a,10);


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

    global Database.QueryLocator start(Database.BatchableContext bc){
String soqlQuery = 'SELECT Name, AccountNumber, Type From Account';
return Database.getQueryLocator(soqlQuery);
} global void execute(Database.BatchableContext bc, List<Account> scope){ for (Account acc : scope){
if(acc.Type.equals('Customer - Direct')){
try{
HttpRequest request = new HttpRequest();
HttpResponse response = new HttpResponse();
Http http = new Http(); String username = 'YourUsername';
String password = 'YourPassword';
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue); request.setHeader('Authorization', authorizationHeader);
request.setHeader('Content-Type', 'application/json');
request.setEndpoint('Your Endpoint URL');
request.setMethod('POST');
request.setBody('Information to Send');
response = http.send(request);
if (response.getStatusCode() == 200) {
String jsonResponse = response.getBody();
System.debug('Response-' + jsonResponse);
}
}
catch(Exception){
System.debug('Error-' + e.getMessage());
}
}
}
} global void finish(Database.BatchableContext bc){ }
}

https://blogs.absyz.com/2017/12/11/making-callouts-with-batch-apex-for-data-of-over-12-mb/

global class mybatchclass Implements Database.Batchable <sObject>,database.stateful,database.allowcallouts {

    //variable to be used in SOQL
public Date today = system.today();
public set<ID> finalaccounts = new set<Id>();
public String SOQL = 'SELECT Id, Name, Type from Account where CreatedDate =: today' ; // Start Method of Batch class
global Database.queryLocator start(Database.BatchableContext bc){
// Query the records
return Database.getQueryLocator(SOQL); } // Execute Method of Batch class
global void execute(Database.BatchableContext bc, List<Account> accountlist) { // Iterate over the list of contacts and get their Account ids
for(Account cc:accountlist){
finalaccounts.add(cc.Id);
} } // Finish Method of Batch class. This is where you make the callout
global void finish(Database.BatchableContext bc) { attachfiles.attachfilestoaccount(finalaccounts);
//make the callout here for getting the attachments data of size greater than 12 MB } }

  

// You can invoke the batch class from the anonymous debug window with the below syntax
mybatchclass mb = new mybatchclass();
Database.executebatch(mb);

  

public class attachfiles(){

 public static void attachfilestoaccount(set<id> listaccount)
{
// First set the callout parameters such as the authToken, Endpoint and the accessToken
String authToken = 'test authorization token';
String authEndpoint = 'test authEndpoint';
String calloutEndpoint = 'test calloutEndpoint';
String accessToken = 'test_act'; // Now make the HTTP callout
Http h1 = new Http();
HttpRequest hreq2 = new HttpRequest();
String dealId = '';
hreq2.setEndPoint(calloutEndpoint);
hreq2.setMethod('POST');
hreq2.setHeader('Content-type','application/xml');
hreq2.setHeader('Authorization','Bearer'+' '+accessToken);
hreq2.setTimeout(30000); hreq2.setBodyAsBlob(Blob.valueOf('testClass')); // Get the response which contains the attachment
HttpResponse res = h1.send(hreq2); List<Attachment> atLst = new List<Attachment>(); for(Account acc:listaccount){
Attachment att1 = new Attachment();
att1.Body = Blob.valueOf(res.getbody());
att1.Name = String.valueOf('Response.txt');
att1.ParentId = acc.Id;
atLst.add(att1);
} // Finally, insert the list
if(atLst.size()> 0)
insert atLst; }
}

http://mysfdc1.blogspot.com/2017/07/how-to-make-http-callouts-in-batch-class.html

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){
}
}

  关于 异步处理的一些限制   :    http://www.salesforcenextgen.com/asynchronous-apex/

088_BatchApex_Callout的更多相关文章

随机推荐

  1. 移动端安卓开发学习记录--Android Studio打断点调试操作步骤记录

    今天我发现一个很迷的事情,我是安卓初学者,发现打印对象的话,打印不出来,但是打印对象的属性值,却可以打印出来,迷啊!!!我好迷茫 咨询大佬后,得知,JAVA打印对象的话,打印出来的不是它自己的内容,而 ...

  2. Java后台如何接收与处理JSON类型数据

    项目开发中偶尔会使用到某个为JSON类型的字段,一个字段中又包含多个其他的字段. 这种设计方式是根据实际需要来进行处理的,比如规则可能包含多条,每一条规则又包含 多个字段:再比如一些特殊的应用场景如标 ...

  3. Java入门与进阶 P-3.5+P-3.6

    计数循环 这个循环需要执行多少次? 循环停下来的时候,有没有输出到最后的0 ? 循环结束后count的值是多少 算数平方 让用户输入一系列的正整数,最后输入-1标识输入结束,然后程序计算出这些数字的平 ...

  4. django框架之drf:04、序列化器常用字段及参数,序列化器高级用法之source、定制字段数据的两种方法、多表关联反序列化的保存、ModelSerializer的使用

    Django框架之drf 目录 Django框架之drf 一.序列化器常用字段及参数 1.常用字段 2.常用字段参数 3.字段参数针对性分类 二.序列化器高级用法之source 1.定制字段名 三.定 ...

  5. 在 SpringBoot 项目中简单实现 JWT 验证

    使用 SpringBoot 提供 api 的时候,我更喜欢使用 jwt 的方式来做验证.网上有会多 Spring Security 整合 jwt 的,也有 Shiro 整合 jwt 的,感觉有点复杂. ...

  6. JAVA虚拟机16-方法的动态调用

    更详细:https://www.cnblogs.com/jthr/p/15762527.html 1.子类重写父类方法 1.1父类 public class Father { public int n ...

  7. Snipaste下载安装(使用教程)

    ## Snipaste下载安装(使用教程)**一 简单介绍** Snipaste 是一个免费简单但强大的截图工具,也可以让你将截图贴回到屏幕上!下载并打开 Snipaste,按下 F1 来开始截图,再 ...

  8. cannot load "mso.dll" vs2008 web开发问题

    已成功解决办法: ①将VS 2008安装包WCUWebDesignerCoreWebDesignerCore.exe提取并重新安装: ②将C:Program Files/Common Files/Mi ...

  9. CMAKE添加库

    1.因为pthread不是C标准库,需要链接 2.在CMakeLists.txt里添加: FIND_PACKAGE(Threads  REQUIRED) TARGET_LINK_LIBRARIES($ ...

  10. SpringCloud 小知识和历史

    六Spring Cloud 回顾之前的: javaSE 数据库 前端 Servlet HTTP Mybatis Spring SpringMVC SpringBoot Dubbo.Zookeeper. ...