Tuesday, February 21, 2017

AX 2009 AX 2012 Call RESTFul API X++ AX2009 AX2012

Below code helps you to call the RestFul API using basic authentication method of adding Authorization header.


static void CallRESTFulAPI(Args _args)
{
    str                             url;
    str                             byteStr;
    System.Net.HttpWebRequest       request;
    System.Net.HttpWebResponse      response;

    System.Byte[]                   byteArray;
    System.IO.Stream                stream;
    System.IO.Stream                dataStream;
    System.IO.StreamReader          streamReader;
    System.Net.ServicePoint         servicePoint;
    System.Net.WebHeaderCollection  httpHeader;
    CLRObject                       clrObj;
    System.Text.Encoding            utf8;
    xml responseXml;
    ;

    byteStr = strfmt('%1:%2', "USERNAME", "PASSWORD");
    new InteropPermission(InteropKind::ClrInterop).assert();
    httpHeader = new System.Net.WebHeaderCollection();
    url = "https://xecdapi.xe.com/v1/convert_from.xml/?from=USD&to=CAD,CHF,CNY,EUR,GBP,HKD,SGD,THB,USD,YEN,&inverse=true";

    clrObj      = System.Net.WebRequest::Create(url);
    request     = clrObj;
    request.set_Method("GET");
    request.set_KeepAlive(true);
    request.set_ContentType("application/xml");
    utf8        = System.Text.Encoding::get_UTF8();
    byteArray   = utf8.GetBytes(byteStr);
    byteStr     = System.Convert::ToBase64String(byteArray);
    httpHeader.Add("Authorization", 'Basic ' + byteStr);

    try
    {
        request.set_Headers(httpHeader);
        response = request.GetResponse();
        dataStream = response.GetResponseStream();
        streamReader = new System.IO.StreamReader(dataStream);
        responseXml  = streamReader.ReadToEnd();
    }
    catch (Exception::CLRError)
    {
        throw error ("Error while connecting API");
    }

    streamReader.Close();
    dataStream.Close();
    response.Close();
}




2 comments: