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的更多相关文章
随机推荐
- 2023牛客寒假算法基础集训营3 A-I+K
A 题解 知识点:贪心. 把所有正偶数除成奇数,即可. (人傻了没加 \(x>0\) WA2 时间复杂度 \(O(n)\) 空间复杂度 \(O(1)\) 代码 #include <bits ...
- SpringMVC学习笔记 - 第二章 - SSM整合案例 - 技术整合、统一结果封装、统一异常处理、前后联调、拦截器
[前置内容]Spring 学习笔记全系列传送门: Spring学习笔记 - 第一章 - IoC(控制反转).IoC容器.Bean的实例化与生命周期.DI(依赖注入) Spring学习笔记 - 第二章 ...
- 解决Java.awt设计GUI程序时Label标签中文乱码解决(idea)
未修改时对话框里边无法显示Label的文本内容,显示的都是方框!网上都是Run--Edit Configurations--VM options:填入-Dfile.encoding=gbk 但是我实际 ...
- 异常的产生过程解析-throw关键字
异常的产生过程解析 先运行下面的程序,程序会产生一个数组索引越界异常ArrayIndexOfBoundException.我们通过图解来解析下异常产生的过程. 工具类 throw关键字 在编写程序时, ...
- MyBatis使用四(查询详解)
本文主要讲述如何在mybatis中进行查询操作[详解] 一. 查询User对象 1.查询单个对象User SelectUser接口声明如下 // 主要条件是使用id public interface ...
- vulnhub靶场之MOMENTUM: 2
准备: 攻击机:虚拟机kali.本机win10. 靶机:Momentum: 2,下载地址:https://download.vulnhub.com/momentum/Momentum2.ova,下载后 ...
- SpringBoot 2.x 在Tomcat8上无法运行,报无法访问错误
非法访问:此Web应用程序实例已停止.无法加载[].为了调试以及终止导致非法访问的 这仅是我的一个Filter重写的时候没有重写他的其他两个方法,导致我在Tomcat8上不能运行,但在Tomcat9上 ...
- el-transfer 数据量过大加载慢卡顿解决办法:el-transfer虚拟滚动懒加载的实现
参考链接 1)https://github.com/GreenHandLittleWhite/blog/issues/152)https://github.com/GreenHandLittleWhi ...
- AEDR8300:光电编码程序构思
一.实验 1.光电反射理论是经过码盘的window时,电压变低,经过bar时,电压为高,这样可以通过检测到的脉冲数,来进行速度的获取.但是实际并不是这样, 反馈回来的信号是周期性的,经过试验发现,可以 ...
- 数据对接:从Notion Database到低代码平台
前言 Notion简介 近几年,有一款叫Notion的产品异常火爆,它是集笔记.任务管理.Wiki.数据管理为一体的产品,他主打两个理念「模块化」和「All-in-one」,Notion最有魅力的还是 ...