Monday, May 30, 2022

How to Call Json Api with POST/GET through X++ using D365 Fin Ops

 Hi  folks, 


Developers most of the time get the requirement of executing POST or GET operations for the JSON API calls in Fin Ops.

A simple X++ code mentioned below can do the work for us : -




class CallJSONAPI
{
    public static str  post(str  _url,str  _jsonstr)
    {
        str     returnresponse;
        
        str							requestJSON, responseJSON, token, tokenJSON, byteStr;

        System.Net.HttpWebRequest		request, requestApi;

        System.Net.HttpWebResponse	response, responseApi;

        System.Byte[]					bytes, bytesApi;

        System.Text.Encoding			utf8, utf8Api;

        System.IO.Stream				requestStream, responseStream, requestStreamApi, responseStreamApi;

        System.IO.StreamReader		streamReader, streamReaderApi;

        System.IO.StreamWriter                 streamWriter;

        System.Exception				ex;

        System.Net.WebHeaderCollection	httpHeader, httpHeaderApi;

        System.IO.Stream				stream;

        new InteropPermission(InteropKind::ClrInterop).assert();

        requestJSON	=_jsonstr;            

        if(requestJSON == '')
        {
            return 'Input JSON is null' ;
        }

        System.Uri uri	                =   new System.Uri(strFmt('%1',_url));

        System.Net.ServicePointManager::Expect100Continue	=   true;

        System.Net.ServicePointManager::set_SecurityProtocol(System.Net.SecurityProtocolType::Tls12);


        httpHeaderApi	    =   new System.Net.WebHeaderCollection();

        requestApi		    =   System.Net.WebRequest::Create(uri);

        requestApi.set_Method("POST"); // You can POST/GET here

        requestApi.set_ContentType("application/json;charset='utf-8'");

        utf8Api		        =   System.Text.Encoding::get_UTF8();

        requestJSON         =   strRem(requestJSON,"'\'");

        bytesApi		    =   utf8Api.GetBytes(requestJSON);

        requestApi.set_Headers(httpHeaderApi);

        requestApi.set_ContentLength(bytesApi.get_Length());

        requestApi.set_ContentType("application/json");

        requestStreamApi	=   requestApi.GetRequestStream();

        requestStreamApi.Write(bytesApi, 0, bytesApi.get_Length());

        responseApi		    =   requestApi.GetResponse();

        responseStreamApi	=   responseApi.GetResponseStream();

        streamReaderApi	    =   new System.IO.StreamReader(responseStreamApi);

        responseJSON	    =   streamReaderApi.ReadToEnd();

        responseStreamApi.Close();

        streamReaderApi.Close();

        responseApi.Close();

        returnresponse  =   responseJSON;

        return  returnresponse;
    }
}


That's all for now. Please let us know your questions or feedback in comments section !!!!

How to reverse Free Text Invoice Voucher entries without Dialog

 Hey Folks ,  This blog post is in continuation of the previous post for Reversing Free Text Invoice Voucher entries with Dialog. Only diffe...