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 :
Finance | Project Operations, Human Resources, ...
Answered

How to send POST request to a third-party website using x++?

(1) ShareShare
ReportReport
Posted on by 206
Hi experts,

I have built a .NET library project for getting an access token for an integration with a third party and I have added the dll file in my D365FO project. I am now trying to use that access token and sending a POST request from x++ to that third party URL but I am getting 400 bad request error in my response.

I have also tested in postman and it's working fine. 

Here is my code and anyone please share your valuable suggestion of what I am doing wrong.
 
public static void main(Args _args)
{
    //Library class for getting access token
    AADAuthClient.Program program = new  AADAuthClient.Program();
    System.Net.WebClient webClient;
    System.Net.WebHeaderCollection headers;
    System.Net.HttpWebRequest request;
    System.Net.HttpWebResponse response;
    str requestBody;
    str responseBody;
    try
    {
        // Create the authentication client
        str accessToken = program.getAccessTokenAsync(tokenEndPoint, clientId, clientSecret);
        if (!accessToken)
        {
            error(/Access token retrieval failed./);
            return;
        }
        headers = new System.Net.WebHeaderCollection();
        // Add the access token to the request headers
        headers.Add(/Authorization/, /Bearer / + accessToken);
        headers.Add(/Content-Type/, /application/json/);
        // Set the request URL
        str apiUrl = /URI/; // Replace with your API endpoint URL
        // Create the HTTP request
        request = System.Net.WebRequest::Create(apiUrl) as System.Net.HttpWebRequest;
        //request.set_Headers(headers);
        request.Method = 'POST';
        //This part is for sending json body
        JSONContract contract = new JSONContract();
        contract.parmBOMId(/string/);
        contract.parmCustRef(/string/);
        //This is a class for handling JSON
        JsonParser jsonParser = new JsonParser();
        str jsonBody = jsonParser.objtoJson(contract);
        using (var streamWriter = new  System.IO.StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(jsonBody);
            streamWriter.Flush();
        }
        // Send the request
        response = request.GetResponse();
        // Read and process the response
        responseBody = response.GetResponseStream().ToString();
        //System.IO.StreamReader streamRead;
        //streamRead = new System.IO.StreamReader(response.GetResponseStream());
        info(/API Response: / + responseBody);
        info(/jsonBody: / + jsonBody);
    }
    catch (Exception::Error)
    {
        error(/An error occurred during authentication or the HTTP request: /); //+ errorTextGet());
    }
}



I will be very thankful to you.
 
I have the same question (0)
  • Verified answer
    Martin Dráb Profile Picture
    237,795 Most Valuable Professional on at
    Let's start by making your code easier to read.
    public static void main(Args _args)
    {
        //Library class for getting access token
        AADAuthClient.Program program = new AADAuthClient.Program();
    
        try
        {
            // Create the authentication client
            str accessToken = program.getAccessTokenAsync(tokenEndPoint, clientId, clientSecret);
            if (!accessToken)
            {
                throw error("Access token retrieval failed.");
                return;
            }
            
            System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();
            // Add the access token to the request headers
            headers.Add("Authorization", "Bearer " + accessToken);
            headers.Add("Content-Type", "application/json");
            
            // Set the request URL
            str apiUrl = "URI"; // Replace with your API endpoint URL
            
            // Create the HTTP request
            System.Net.HttpWebRequest request = System.Net.WebRequest::Create(apiUrl) as System.Net.HttpWebRequest;
            //request.set_Headers(headers);        
            request.Method = 'POST';
            
            //This part is for sending json body
            JSONContract contract = new JSONContract();
            contract.parmBOMId("string");
            contract.parmCustRef("string");
            
            //This is a class for handling JSON
            JsonParser jsonParser = new JsonParser();
            str jsonBody = jsonParser.objtoJson(contract);
            using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
            {
                streamWriter.Write(jsonBody);
                streamWriter.Flush();
            }
            
            // Send the request
            System.Net.HttpWebResponse response = request.GetResponse();
            
            // Read and process the response
            str responseBody = response.GetResponseStream().ToString();
            
            //System.IO.StreamReader streamRead;
            //streamRead = new System.IO.StreamReader(response.GetResponseStream());
            info(strFmt("API Response: %1", responseBody));
            info(strFmt("jsonBody: %1", jsonBody));
        }
        catch (Exception::Error)
        {
            error(/An error occurred during authentication or the HTTP request: /); //+ errorTextGet());
        }
    }
    Now please tell us where the exception is thrown. I'm assuming it's either somewhere in getAccessTokenAsync(), or in request.GetResponse().
     
    By the way, I noticed that you created headers, but you aren't using them (because the call of set_Headers() is commented out. You suggested that the authentication in required, therefore this must be a bug.
  • Arif Hussain Profile Picture
    206 on at
    Sir Martin Dráb,

    Thank you for your kind response. I really tried to paste the code inside code snippet but it was coming all in one line, I do not know why. I also tried to correct the spaces as well but still it was difficult for me that's why I pasted the code in simple way. 

    Btw sir, I figured it out, I was not sending the correct json body for which it was giving error in request.GetResponse(). 

    Yeah, it's my mistake I did not commend out the set_headers part. I was just debugging and commented that for testing purpose and I forgot to comment it out.

    Btw, thank you so much again sir. You have always helped me for which I really appreciate. 

    Sir, I also want you to help me in my this question please. I have still confusion in that.

    Here is the link.
    https://community.dynamics.com/forums/thread/details/?threadid=8db8f1aa-fc5c-ee11-be6f-00224827e220

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 > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 663 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

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

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 348 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans