088_BatchApex_Callout
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的更多相关文章
随机推荐
- Add All&shuffle-sort(List)
Add All&shuffle Collections常用功能 java.utils.collections是集合工具类,用来对集合进行操作.部分方法如下︰ public static < ...
- 【分析笔记】全志平台 TWI 上拉电压异常的问题
记录说明 原本这么简单的芯片,没有必要做记录,后来发现其中有一颗单独挂在 TWI2 无法通信,而主要原因是最容易忽视的电源域的问题,因此记录一下这件事情. 芯片介绍 MCP3021 是一颗 10BIT ...
- Vue20 生命周期
转:https://blog.csdn.net/weixin_45791692/article/details/124045505 1 简介 Vue的生命周期就是vue实例从创建到销毁的全过程,也就是 ...
- 微信小程序 添加域名
1.不校验合法域名.web-view (业务域名).TLS版本以及 HTTPS证书 2.小程序上的请求=>服务器的根地址=>都需要添加微信公众平台(否则会无法发送请求,导致代码报错)
- vue3 vite 使用NProgress.js纳米级进度条
NProgress.js 官网:https://ricostacruz.com/nprogress/ 安装方式: npm install nprogress 使用方法 在router 的index.j ...
- pdf转MD、HTML、word网址收集
PDF 转 Word,Excel,PPT,JPG 的网址:https://smallpdf.com/cn/pdf-to-word PDF 转 Markdown 的网址:https://pdf2md.m ...
- LG P5043 树同构
\(\text{problem}\) 无根树同构的判断 \(\text{Analysis}\) 考虑树哈希,注意使用较正确的哈希方法 无根树同构有个性质 只要判断以这两棵树的重心为根是否同构即可 \( ...
- JZOJ 4213. 【五校联考1day2】对你的爱深不见底
题目 思路 结论题,我不会证明: 找到第一个 \(|S_n| \leq m + 1\),那么答案就是 \(m - |S_{n-2}|\) 证明?我说了我不会,就当结论用吧 这已经很恶心了 然而这题还要 ...
- 大规模 IoT 边缘容器集群管理的几种架构-5-总结
前文回顾 大规模 IoT 边缘容器集群管理的几种架构-0-边缘容器及架构简介 大规模 IoT 边缘容器集群管理的几种架构-1-Rancher+K3s 大规模 IoT 边缘容器集群管理的几种架构-2-H ...
- day06-动态SQL语句
动态SQL语句 1.基本介绍 官方文档 mybatis – MyBatis 3 | 动态 SQL 为什么需要动态SQL? 动态SQL是MyBatis的强大特性之一 使用 JDBC 或其他类似的框架,根 ...