Tuesday, February 14, 2023

Trigger the API using X++

 Trigger the API using X++.


using System.IO;
using System.Net;
using System.Text;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.File;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Threading.Tasks;

    Way 1 : With Encoding the JSON

public void callAPI()
{
    WebException                exception;
    HttpWebRequest              webRequest;
    WebResponse                 webResponse;
    CLRObject                   clrObj;
    System.Exception            ex;
    System.Byte[]               bytes;
    System.Text.Encoding        encoding;
    #OCCRetryCount
        

    webRequest                  = System.Net.WebRequest::Create('URL');
    webRequest.Method           = 'MethodName';// POST / Get
    webRequest.KeepAlive        = true;
    webRequest.ContentType      = 'ContentType';//"application/json"
    webRequest.Timeout          = maxInt();

    System.Net.WebHeaderCollection headers = new System.Net.WebHeaderCollection();

    Headers = webRequest.Headers;
    headers.Add('Authorization', 'Bearer ' + token);

	// With Encoding
    if (reqJson)
    {
        encoding    = System.Text.Encoding::get_UTF8();
        bytes       = encoding.GetBytes(reqJson);

        webRequest.ContentLength = bytes.get_Length();

        using (Stream stream = webRequest.GetRequestStream())
        {
            stream.Write(bytes,0,bytes.get_Length());
            stream.Close();
        }
    }

    if (webRequest != null)
    {
        webResponse = webRequest.GetResponse();

        using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream()))
        {
            str response = streamReader.readToEnd();
        }

        webResponse.Close();

    }
    else
    {
        throw new System.Exception("Please provide valid URL");
    }
}

    Way 2 : Without Encoding the JSON

public void callAPI()
{
    System.Net.HttpWebRequest       request;
    System.Net.HttpWebResponse      response;
    CLRObject                       clrObj;
    System.Exception                ex;
    System.Net.WebHeaderCollection  httpHeader;
    str                             requestJson, responseJson;

    try
    {
        // We can use commented code also
        //new InteropPermission(InteropKind::ClrInterop).assert();
        //clrObj = System.Net.WebRequest::Create('Url');
        //request = clrObj;

        request  = System.Net.WebRequest::Create('URL');
        request.Method      = "POST";
        request.ContentType = "application/json";
           
        // Adding header in 2 ways 
        httpHeader = new System.Net.WebHeaderCollection();

		// Way 1: Get the header from request
        httpHeader = request.Headers;
        httpHeader.Add("Authorization", 'Token');
        httpHeader.Add('key:' + 'Key');//If your API need any mandatory tags that time this is needed. 
		
		//  Way 2: assign header to request
        //request.set_Headers(httpHeader);

        //Upload Json
        //System.IO.Stream    requestStream = request.GetRequestStream();
        using (System.IO.StreamWriter   streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
        {
            streamWriter.Write(requestJson); // writing JSON
            streamWriter.Flush();
            streamWriter.Close();
        }
        if (request != null)
        {
            response = request.GetResponse();
            using (System.IO.StreamReader responseStream = new System.IO.StreamReader(response.GetResponseStream()))
            {
                responseJson = responseStream.ReadToEnd().ToString();

                info(responseJson);
            }
        }
    }
}


https://msdax.wordpress.com/2018/04/30/ax-2012-call-restful-api-using-basic-authentication-x-dynamics-ax-2012/

Keep Daxing!!

No comments:

Post a Comment