Code:
global class CurrencyExchangeRateScheduler implements Schedulable
{
public String sessionId;
public CurrencyExchangeRateScheduler()
{
String username = 'username';
String password = 'password+security_token';
partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap();
partnerSoapSforceCom.LoginResult loginResult = sp.login(username, password);
sessionId = loginResult.sessionId;
}
global void execute(SchedulableContext ctx)
{
UpdateDailyCurrencyExchangeRate(sessionId);
}
@Future(callout=true)
public static void UpdateDailyCurrencyExchangeRate(string sessionId)
{
system.debug('sessionId: '+sessionId);
...
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'OAuth ' + sessionId);
req.setHeader('Content-Type', 'application/json');
req.setMethod('POST');
for(CurrencyType currType : currencies)
{
if(!currType.IsCorporate)
{
req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v28.0/sobjects/CurrencyType/'+currType.id+'?_HttpMethod=PATCH');
req.setBody('{ "ConversionRate" : 2.5 }');
HttpResponse response = h.send(req);
system.debug('response: '+response);
}
}
}
}
Debug: response: System.HttpResponse[Status=Unauthorized, StatusCode=401]
I also tried with the Authorization header as Bearer
+ sessionId.
But again the same issue.
The code works perfectly fine when I am loggedin to the org. But when the class is scheduled and I am not loggedin, the response status is 'Unauthorized' and the currency table is not updated.
How can I get the session Id when User is not loggedin?