function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
EllEll 

Get the time before and after a HTTPRequest

Hey guys,

I was wondering if anyone has tried getting a timestamp before and after a HTTPRequest? I want to create a record to log each transaction to a third-party system with a 'Start' and 'End' time. I could add the 'End' time into the response of the request, but wondered if there was a way to get it in Apex, as using DateTime.now() seems to give the same value before + after.

I have a @Future method calling some code that basically follows a format of:

Create an empty record with the start time as DateTime.now();
Run a HttpRequest
Set the record's end time as DateTime.now(), along with some data from the response
Insert the record

i.e.
// create log
Log__c log = new Log__c();
log.Start_Time__c = DateTime.now();

// send request
HttpRequest req = new HttpRequest();
req.setEndpoint('URL');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);

// update log
log.Response__c = res.getBody();
log.Status__c = res.getStatusCode();
log.End_Time__c = DateTime.now();
insert log;
But both the DateTime.now() stamps are exactly the same. I thought that as the request has been processed (due to values being on the record from the response) that the second DateTime.now() would have the time after request, but is that not how it works in this context?

Cheers
Raj VakatiRaj Vakati
try this pls
 
// create log
Log__c log = new Log__c();
log.Start_Time__c = DateTime.now();

// send request
HttpRequest req = new HttpRequest();
req.setEndpoint('URL');
req.setMethod('GET');
Http http = new Http();
HttpResponse res = http.send(req);
if(res.getStatusCode()==200){
// update log
log.Response__c = res.getBody();
log.Status__c = res.getStatusCode();
log.End_Time__c = DateTime.now();
insert log;
}

 
EllEll
Thanks for that!

I realised that it didn't show purely because the timescale was so quick, it was ms rather than s. When I increased the delay it worked fine either way!