Skip to main content

Notifications

Finance | Project Operations, Human Resources, ...
Answered

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

Posted on by 155
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.
 
  • Arif Hussain Profile Picture
    Arif Hussain 155 on at
    How to send POST request to a third-party website using x++?
    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
  • Verified answer
    Martin Dráb Profile Picture
    Martin Dráb 229,302 Most Valuable Professional on at
    How to send POST request to a third-party website using x++?
    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.

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

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Complete!

🔔 Be sure to subscribe to the new forums you are interested in to stay up to date! 🔔

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,902 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 229,302 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Product updates

Dynamics 365 release plans