I build an apex rest API that is returning base64 to client. API works fine with PostMan/soapUI. When i try to invoke same Apex REST API from my another developer Account I am getting HttpResponse[Status=Unauthorized, StatusCode=401]"|. Initially I was getting Return code 302 and in debug log i saw it was redirecting to domain URL and then i changed End point to domain URL so return code 302 does not appear but now keep getting 401. I checked Salesforce documentation but unable to find anything specific to 401 error code.
Any idea if i am doing something wrong in my code ?
HttpRequest tokenRequest = new HttpRequest();
tokenRequest.setMethod('POST');
tokenRequest.setEndpoint('https://test.salesforce.com/services/oauth2/token');
String CLIENT_ID = ‘xxxxxxxxxxxxxxxx’;
String CLIENT_SECRET = ‘xxxxxxxxxxxxxxxx’;
String USERNAME = ‘xxxxxxxxxxxxxxxx’
String PASSWORD = ‘xxxxxxxxxxxxxxxx’
tokenRequest.setBody('grant_type=password' + '&client_id='+CLIENT_ID +
'&client_secret='+CLIENT_SECRET + '&username='+USERNAME + '&password='+PASSWORD);
Http http1 = new Http();
HTTPResponse responseToken = http1.send(tokenRequest);
string tran = ‘xxxxxxx03zsTNQAY'; // for test purpose only
string endpoint = 'https://xxxxx--xxxxxxx.my.salesforce.com/services/apexrest/v1/getdetails?transactionid='+tran;
HttpRequest request = new HttpRequest();
request.setHeader('Content-Type', 'application/json');
request.setHeader('Authorization', 'Bearer ' +responseToken.getBody());
request.setEndpoint(endpoint);
request.setMethod('GET');
Http http = new Http();
HTTPresponse res= http.send(request);
/* Added to handle 302 return code
while (res.getStatusCode() == 302) {
request.setEndpoint(res.getHeader('Location'));
res = new Http().send(request);
system.debug('Calling Again !!! ');
}
*/
system.debug(' Location header from respose :'+ res.getHeader('Location'));
system.debug(' Response :'+ res);
} catch(exception e){
System.debug('ERROR: '+ e.getMessage());
}
The HTTP 401 Unauthorized client error status response code indicates that the request has not been applied because it lacks valid authentication
https://xxxxx--xxxxxxx.my.salesforce.com/services/apexrest/v1/getdetails?transactionid='+tran
is failing ?