i am doing an callout to a third parity using a trigger. and I am getting the error.

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY message: LeadCallout: execution of AfterInsert caused by: System.NullPointerException: Argument cannot be null. Class.System.EncodingUtil.urlEncode: line 30, column 1 Class.PostLeadtoBP.makePostLeadtoBP: line 13, column 1 Trigger.LeadCallout: line 3, column 1 errorCode: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY

This is the error I got from workbench doing a test with Rest Explore post to the Lead API. here is my Trigger:

trigger LeadCallout on Lead (after insert) {
    For (Lead l: Trigger.new){
        PostLeadtoBP.makePostLeadtoBP(l.Id, l.Phone);              

Here is the Class:

public class PostLeadtoBP {
    public static void makePostLeadtoBP(String leadId, String phoneNo){
        Http http = new Http();
        HttpRequest req = new HttpRequest();
            long unixTime = System.currentTimeMillis() / 1000L;
        HttpResponse res = new HttpResponse();
        // Set Header for the Authorization
        req.setHeader('Content-Type', 'application/json;charset=UTF-8');
        req.setHeader('Authorization', '********************* appId=\"*********************\", clientId=\"WebChat\"' );
        // Set the body as a JSON object
        req.setBody(',parameters: {LeadID='+EncodingUtil.urlEncode(leadId,'UTF-8')+'phone='+EncodingUtil.urlEncode(phoneNo,'UTF-8') );
        req.setCompressed(true); // otherwise we hit a limit of 32000
         try {
            res = http.send(req);
        } catch(System.CalloutException e) {
            System.debug('Callout error: '+ e);

This error is fairly self-explanatory. You're passing a null value to EncodingUtil.urlEncode and that's not allowed. You only call that method at one location:

req.setBody(',parameters: {LeadID='+EncodingUtil.urlEncode(leadId,'UTF-8')+'phone='+EncodingUtil.urlEncode(phoneNo,'UTF-8') );

Since this Lead's Id cannot be null in an after insert context, the phone number is your culprit.

You need to add logic to handle a null value, such as skipping this record or supplying a default, like an empty string.

However, once you fix that problem you're going to get another error, because you cannot make callouts synchronously from a trigger context. You'll need to mark that callout method @future or use another form of Asynchronous Apex to push the callouts into another transaction.

Note also that the future method limit in a transaction is 50. By adopting this architecture, you're severely constraining the number of records you can process in a transaction, and leaving the door open to limits problems very quickly.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.