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的更多相关文章
随机推荐
- StringBuilder的原理-append方法
StringBuilder的原理 append方法 根据StringBuilder的API文档,常用构造方法有2个:public stringBuilder():构造一个空的StringBuilder ...
- ThinkPad E580 装Ubuntu系 系统无WIFI 解决办法
首先得下载 最新的驱动,我之前因为自己的下载的驱动不够新,导致我的驱动一直装不上去 https://github.com/tomaspinho/rtl8821ce 这个是最新的驱动的下载 地址,建议从 ...
- 力扣每日一题2023.1.16---1813. 句子相似性 III
一个句子是由一些单词与它们之间的单个空格组成,且句子的开头和结尾没有多余空格.比方说,"Hello World" ,"HELLO" ,"hello w ...
- C++ 练习7 引用作为函数返回值
当引用作为函数的返回值时,可以直接将其当作赋值语句的左值使用 如:函数refValue(int& x)可以像 a=10 中的"a"来使用 1 #include <io ...
- CF335F Buy One, Get One Free
\(\text{Solution}\) 其实不想写(因为不好写... 所以贴贴 \(\text{Solution}\) 然而就关于这题而言讲得也不太清楚 可撤销贪心就是维护当前状态的最优解,同时考虑以 ...
- .Net6 微服务之Ocelot+IdentityServer4入门看这篇就够了
前言 .Net 6 使用 Consul 实现服务注册与发现 看这篇就够了.Net6 使用 Ocelot + Consul 看这篇就够了.Net6 微服务之Polly入门看这篇就够了 书接上文,本文将继 ...
- PostGIS之几何有效性
1. 概述 PostGIS 是PostgreSQL数据库一个空间数据库扩展,它添加了对地理对象的支持,允许在 SQL 中运行空间查询 PostGIS官网:About PostGIS | PostGIS ...
- 基于JavaScript的OpenGL 01 之Hello Triangle
1. 引言 本文基于JavaScript语言,描述OpenGL(即,WebGL)的绘制流程,这里描述的是OpenGL的核心模式(Core-profile) 笔者这里不过多描述每个名词.函数和细节,更详 ...
- PostgreSQL 实现快速删除一个用户
一.具体方法 一般情况下直接执行 drop role xxx; 就可以把这个用户删除.但是很多时候会因为用户有依赖而报错. 二.权限依赖 postgres=# create role test wit ...
- 线程join detach 僵尸线程
进程死亡后,由父进程负责回收PCB资源,不回收则会出现僵尸进程 对于线程来说,任何一个线程都可以回收另一个线程的资源 在子线程终止后,通常在主线程中通过pthread_join来回收子线程的资源,获取 ...