+ Start a Discussion
D VelD Vel 

Apex Call out throws error

I trying to test the Apex Call outs which uses the OAuth Authentication. I am not sure what I am missing here it throws error on the line HttpResponse res1 = http1.send(req1); like 

Line: 22, Column: 1
System.UnexpectedException: java.lang.IllegalArgumentException: invalid start or end
public class TestD365API {
    public final String clientId = 'xxxxxxxxxxxxx';
    public final String clientSecret = 'xxxxxxxx';
    
    public String getD365Customer(){             
        String reqbody = 'grant_type=client_credentials&client_id='+clientId+'&client_secret='+clientSecret;
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://login.microsoftonline.com/tenant/oauth2/token');
        HttpResponse res = h.send(req);
        deserializeResponse resp1 = (deserializeResponse)JSON.deserialize(res.getbody(),deserializeResponse.class);
        String atoken = resp1.access_token;
        
        
        Http http1 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setEndpoint('https://dev-xyz/data/Customers');
        req1.setMethod('GET');
        req1.setHeader('Authorization','Bearer '+atoken);
        HttpResponse res1 = http1.send(req1);
        System.debug('Response Body=========' + res1.getBody());
        return res1.getBody();   
    }  
    
    public class deserializeResponse
    {
        public String token_type;
        public String expires_in;
        public String ext_expires_in;
        public String expires_on;
        public String not_before;
        public String resource;
        public String access_token;
    }
}
Please help me fixing this issue.
Suraj MakandarSuraj Makandar
Hi D Vel,

IllegalArgumentException is thrown when an illegal argument was provided to a method call. For example, a method that requires a non-null argument throws this exception if a null value is passed into the method.

Please check all the headers/parameters for you API calls and their values being passed.

Thanks,
Suraj
Herbert KaluleHerbert Kalule
Hi DVel,
Did you find any soluiton to this error? Please share some feedback.

Thanks.
Herbert
Alejandro BraunschweigAlejandro Braunschweig

Hello D Vel,

Suraj's point is rather valid; first of all you must make sure you have a body to parse. Beyond that, if you are only consuming the "access_token" part of the response, there is no need to include the other properties in your "deserializeResponse" class declaration.

Sugestion, I always evaluate the response's status code, and only try to parse it if it is what I expect, e.g.

...
if (resp.getStatusCode() == 200)  { tknData = (TokenData)JSON.deserialize(respBody, TokenData.class); }
...

/**@description This class is meant to serve as a placeholder for token data */
public class TokenData {
    public String access_token { get; set; }
}
Cheers!