• Rahul Sethi 26
  • NEWBIE
  • 0 Points
  • Member since 2022

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
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);
              
            System.debug(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.setEndpoint('https://qa.suppliergateway.com:8446/v1/api/dataenrichment/jobs');
               request.setMethod('POST');
               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;
                    }
                            else{
                    
                System.debug('Not Ok! Data Enrichment Job ID::' + response);    
            
            }
        }

    }