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
Rahul Sethi 26Rahul Sethi 26 

System.HttpResponse[Status=Unauthorized, StatusCode=401]?

I am getting unauthorized error when trying to fetch token from a custom object. It shows correctly in Raw logs after running, but while adding it to setheader method of the Httprequest, it is throwing 401 error. If I hard code in a string, then it is working fine. But, I need to query it and then put it in the header.

public class SupplierGatewayEnrichment {
    public void createDataEnrichment(){
            List<SG_Token__c> bearer_token = [Select Token__c from SG_Token__c where createddate = TODAY limit 1];
             String token = String.valueOf(bearer_token);
      //  String token2 = 'Q8e90uS-BQjb9ExORzBchScwBjgahCmbze_5mZufysMALG7k65K-nlfjJuuoBaRtiPfJYQaLzMykGtCx47BIZNWDpuqkkA6qn_uuwe23J3pXHShhL7A2AP7A_4vO1NB_D8eg9rhcZE2hdvgUZDPjUVcqWMySLXhBQ6anv6XF5P1_1aWCZmGObVKop5nYJGxB0Ril3gTvYWGonRFlVAMImPVVByFJvGAh-Cmm_atvvU1qN8PJr8hIU_goaR5i8tdMPxV-ukFrHiWaOqgJ790VWQBbsV2cvjVJTsqqy6CRlNc2dEDk5ZuvgAtoIdR0zQBIovhfu2y53CbyuLnS0PBBiV81zHEK0s-QKRTCsh1iE8Wx1ujkjYddqYeICqpNFLMOdKMsLbVIw7v0hmO0_MKA3O-wiSoRvYptLHsR36dB2QIvsgF0ayt55Er0dAj9hRLtqJ_tmmsAYj7ujDo9GjQfGvuf480ORPIe8_Np6Hp9i-_86vNFF6CpQ';
       //        System.debug(token2);
            Http http = new Http();
              HttpRequest request = new HttpRequest();
               request.setHeader('Authorization', 'Bearer '+ token);
            request.setHeader('Content-Type', 'application/json;charset=UTF-8');
            request.setBody('{ "jobdesc": ""}');
            HttpResponse response = new HttpResponse();
            response = http.send(request);
              if(response.getStatusCode() == 200){
                System.debug('Successful Data Enrichment Job ID::' + response);
                // Deserializes the JSON string
                SGEnrichment_Wrapper parsedJSON = SGEnrichment_Wrapper.parse(response.getBody());
                String final_jobid = parsedJSON.Job.jobid;
                    SGEnrichment__c enrichment = new SGEnrichment__c();
                    enrichment.JobID__c    = final_jobid;
                    insert enrichment;
                System.debug('Not Ok! Data Enrichment Job ID::' + response);    

SwethaSwetha (Salesforce Developers) 
Can you confirm you have added the endpoint URL' to the remote site setting?

If this information helps, please mark the answer as best. Thank you
Rahul Sethi 11Rahul Sethi 11

Hi @swetha,

The API works fine when the actual token value is used as a variable i.e. token2 string (which I commented out). I can confirm the Remote site settings are fine.

It is not working when we are fetching the token from a text area field of a custom object. The size of the token does not exceed 550 characters so I doubt it is a heap size issue.