Showing posts with label Web service AX. Show all posts
Showing posts with label Web service AX. Show all posts

Wednesday, June 15, 2016

Using XE Currency Restful API in AX - Using Basic Authentication method



static void XECurrencyConverionRestfulAPI(Args _args)
{
    System.Net.HttpWebRequest           webReq;
    System.Net.HttpWebResponse          webRes;
    CLRObject                           clrObj;
    System.IO.Stream                    stream;
    System.IO.StreamReader              streamRead;
    System.IO.StreamWriter              streamWrite;
    System.Net.ServicePoint             servicePt;
    System.Net.WebHeaderCollection      headers = new System.Net.WebHeaderCollection();
    str                                 userNamePassword, userNamePassword64, ret;
    System.Byte[]                       byte;
    System.Text.Encoding                encoding = System.Text.Encoding::get_UTF8();
 
    //This line gives the user control to run unmanaged and managed code
    new InteropPermission(InteropKind::ClrInterop).assert();
    // Create Object for adding headers
    headers = new System.Net.WebHeaderCollection();
    clrObj = System.Net.WebRequest::Create('https://xecdapi.xe.com/v1/currencies.xml');
    webReq = clrObj;
    //Set Method Type
    webReq.set_Method("GET");
    webReq.set_KeepAlive(true);
    // Set Content type
    webReq.set_ContentType("application/xml");
 
    try
    {
        userNamePassword = 'YOURUSERNAME:YOURPASSWORD';
        //64 bit encode user name and password
        byte = encoding.GetBytes(userNamePassword);
        userNamePassword64 = System.Convert::ToBase64String(byte);
        headers.Add("Authorization", 'Basic ' + userNamePassword64);
 
        //Add header to request
        webReq.set_Headers(headers);
        //Gets the response object
        webRes = webReq.GetResponse();
    }
    catch (Exception::CLRError)
    {
        //Access the last CLR Exception
        info(CLRInterop::getLastException().ToString());
     
        //See AifUtil::getClrErrorMessage for another alternative
        //how to parse the Exception object
    }
    //Get Stream
    stream = webRes.GetResponseStream();
    streamRead = new System.IO.StreamReader(stream);
    ret = streamRead.ReadToEnd();
    stream.Close();
    webRes.Close();
}