web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Unanswered

Getting 401 unauthorised error while consuming external APIs in x++ D365fo

(3) ShareShare
ReportReport
Posted on by 40
Hi all , i am posting some data from my d365fo to external system as part of my outbound integration through custom services using x++
i am able to generate the token, but while doing 'POST' method, i am getting this 401 unauthorised exception, even though i have successfully generated the token.attaching the code snippet
 
        public static void main(Args _args)
   
        {
            System.Net.HttpWebRequest        request;
            System.Net.WebResponse           response;
            System.IO.Stream                 responseStream,
                                             requestStream;
            System.IO.StreamReader           streamReader;
            System.Text.Encoding             utf8;
            System.Byte[]                    bytes;
            System.Exception                 ex;
            Notes                            token,
                                             requestJson,
                                             responseJson;
            //MDIntegrationResponse          apiAck;
            Techno_SLIntegrationParameters   parameters;
            System.Net.WebException          webException;
   
            System.Net.WebHeaderCollection httpHeader = new System.Net.WebHeaderCollection();
            //select firstonly parameters;
            str endpointURL = "https://dev.bridge.scatterlink.com/product-receipts";
            Techno_SLProductReceiptOutboundPostingService techno = new Techno_SLProductReceiptOutboundPostingService();
            token = techno.generateAccessToken();
            info(token);
            //token = this.generateAccessToken();
            if(token)
            {
                new InteropPermission(InteropKind::ClrInterop).assert();
                request = System.Net.WebRequest::Create(endpointURL);
                utf8 = System.Text.Encoding::get_UTF8();
                //requestJson = FormJsonSerializer::serializeClass(_request);
                requestJson = '{"LegalEntityId": "mmo","PurchaseOrderId": "PO00084373","ProductReceiptId": "9173","ProductReceiptCreatedDateTime": "","Status": "Processed","Message": "","Error Code": "","TransactionId": "","lines": [{"PurchaseOrderId": "PO00084378","ProductReceiptId": "91836","LotId": "MMO-224291","ItemId": "10000003","Quantity": 5,"ProcurementCategory": "Pumps","Site": "100","Warehouse": "100","Location": "01A01","SerialNumber": "SN002","TransactionId": ""}]}';
                                                                
                bytes = utf8.GetBytes(requestJson);
                //httpHeader.Add('Authorization', 'Bearer'+ token);
                httpHeader.Set('Authorization', 'Bearer '+ token);
                request.set_Headers(httpHeader);
                //request.set_Method('POST');
                request.Method = "POST";
                //request.set_Headers(httpHeader);
                request.ContentType = 'application/json';
                request.UseDefaultCredentials = true;
                request.PreAuthenticate = true;
                //request.Credentials = credentialcache.
           
                request.set_ContentLength(bytes.get_Length());
                requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.get_Length());
                try
                {
                response = request.GetResponse();
                responseStream = response.GetResponseStream();
                streamReader = new System.IO.StreamReader(responseStream);
                responseJson = streamReader.ReadToEnd();
                info(strFmt('%1', responseJson));
                }
                catch(webException)
                {
                    if (webException.get_Response() != null)
                    {
                        System.Net.HttpWebResponse httpWebResponse;
                        Notes responseString;
                        // Get error response stream
                        httpWebResponse = webException.get_Response() as System.Net.HttpWebResponse;
                        responseStream = httpWebResponse.GetResponseStream();
                        streamReader = new System.IO.StreamReader(responseStream);
                        responseString = streamReader.ReadToEnd();
                        // Log the error response body (usually in JSON format)
                        error(strFmt("Error Response (JSON): %1", responseString));
                        // Close resources
                        streamReader.Close();
                        responseStream.Close();
                        httpWebResponse.Close();
                    }
                    else
                {
                    // Log the exception message if no response
                    error(strFmt("WebException occurred: %1", webException.get_Message()));
                }
                }
        
              
            }
                
        }
} -- can someone suggest what might i be missing.Have been trying since morning but no luck.
Categories:
I have the same question (0)
  • Martin Dráb Profile Picture
    238,308 Most Valuable Professional on at
    Are you sure that the token gives you necessary permissions?
     
    Let me simplify your code a bit, so it's easier to read.
    public static void main(Args _args)
    {  
        str endpointURL = "https://dev.bridge.scatterlink.com/product-receipts";
        str token = new Techno_SLProductReceiptOutboundPostingService().generateAccessToken();
        
        if (!token)
        {
            return;
        }
        
        System.Net.HttpWebRequest request = System.Net.WebRequest::Create(endpointURL);
        System.Text.Encoding utf8 = System.Text.Encoding::UTF8;
        str requestJson = '{"LegalEntityId": "mmo","PurchaseOrderId": "PO00084373","ProductReceiptId": "9173","ProductReceiptCreatedDateTime": "","Status": "Processed","Message": "","Error Code": "","TransactionId": "","lines": [{"PurchaseOrderId": "PO00084378","ProductReceiptId": "91836","LotId": "MMO-224291","ItemId": "10000003","Quantity": 5,"ProcurementCategory": "Pumps","Site": "100","Warehouse": "100","Location": "01A01","SerialNumber": "SN002","TransactionId": ""}]}';
                                                        
        System.Byte[] bytes = utf8.GetBytes(requestJson);
    
        System.Net.WebHeaderCollection httpHeader = new System.Net.WebHeaderCollection();
        httpHeader.Set('Authorization', 'Bearer '+ token);
        request.Headers = httpHeader;
        request.Method = "POST";
        request.ContentType = 'application/json';
        request.UseDefaultCredentials = true;
        request.PreAuthenticate = true;
    
        request.ContentLength = bytes.Length;
        System.IO.Stream requestStream = request.GetRequestStream();
        requestStream.Write(bytes, 0, bytes.Length);
        
        System.IO.Stream responseStream;
        System.IO.StreamReader streamReader;
        System.Net.WebException webException;
        
        try
        {
            System.Net.WebResponse response = request.GetResponse();
            responseStream = response.GetResponseStream();
            streamReader = new System.IO.StreamReader(responseStream);
            str responseJson = streamReader.ReadToEnd();
            info(strFmt('%1', responseJson));
        }
        catch(webException)
        {
            if (webException.Response != null)
            {
                // Get error response stream
                System.Net.HttpWebResponse httpWebResponse = webException.Response as System.Net.HttpWebResponse;
                responseStream = httpWebResponse.GetResponseStream();
                streamReader = new System.IO.StreamReader(responseStream);
                str responseString = streamReader.ReadToEnd();
                // Log the error response body (usually in JSON format)
                error(strFmt("Error Response (JSON): %1", responseString));
                // Close resources
                streamReader.Close();
                responseStream.Close();
                httpWebResponse.Close();
            }
            else
            {
                // Log the exception message if no response
                error(strFmt("WebException occurred: %1", webException.get_Message()));
            }
        }
    }
    
    HttpWebRequest is obsolete - use HttpClient instead.
     
    Also, I've noticed that you don't dispose resources correctly. You never call Close() (or Dispose()) for the objects created in the try block and in catch, you
    close them only if the block doesn't throw an exception. You should utilize either using blocks, or try/finally. It's not something that can resolve your problem with authorization, but it's worth mentioning when we're talking about the code.
     
  • Anthony Blake Profile Picture
    2,979 Super User 2025 Season 2 on at
     
    The error suggests there is an issue with the Authorizastion header. I can see that you have set it in your code, so it's not because it is missing.
     
    Have you managed to connect to the API via a testing tool such as Postman to check that your credentials and authorization are correct?
     
    Anthony

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

News and Announcements

Season of Giving Solutions is Here!

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Abhilash Warrier Profile Picture

Abhilash Warrier 843 Super User 2025 Season 2

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 467 Super User 2025 Season 2

#3
Martin Dráb Profile Picture

Martin Dráb 338 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans