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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Unanswered

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

(0) ShareShare
ReportReport
Posted on by 32
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)
  • Anthony Blake Profile Picture
    2,963 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

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 > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Siv Sagar Profile Picture

Siv Sagar 93 Super User 2025 Season 2

#2
#ManoVerse Profile Picture

#ManoVerse 76

#3
Martin Dráb Profile Picture

Martin Dráb 66 Most Valuable Professional

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans