最新消息:ww12345678 的部落格重装上线,希望大家继续支持。

AX 2012 X++使用基本身份验证调用Restful API / AX 2012 Call Restful API using basic authentication X++ Dynamics AX 2012

网络文摘 William 157浏览 0评论
Below code helps you to call the Restful API using basic authentication method of adding Authorization header using HTTP Post method.
 static void ConsumingRestService(Args _args)  
 {  
   str destinationUrl = 'Json Url here', requestXml, responseXml;  
   System.Net.HttpWebRequest    request;  
   System.Net.HttpWebResponse   response;  
   CLRObject            clrObj;  
   System.Byte[]          bytes;  
   System.Text.Encoding      utf8;  
   System.IO.Stream        requestStream, responseStream;  
   System.IO.StreamReader     streamReader;  
   System.Exception        ex;  
   System.Net.WebHeaderCollection httpHeader;  
   str               byteStr;  
   System.Byte[]          byteArray;  
   System.IO.Stream        stream;  
   System.IO.Stream        dataStream;  
   byteStr = strfmt('%1:%2', "USERNAME", "PASSWORD");  
   requestXml = " { \"storeId\": 25001, \"terminalId\":\"012\", \"transactionSequenceNumber\":\"031949640279\", \"lookup\" : { \"nameSearch\" : { \"lastName\" : \"Jones\",\"zipCode\" : \"214034702\" } } }";  
   try  
   {  
     new InteropPermission(InteropKind::ClrInterop).assert();  
     httpHeader = new System.Net.WebHeaderCollection();  
     clrObj = System.Net.WebRequest::Create(destinationUrl);  
     request = clrObj;  
     utf8 = System.Text.Encoding::get_UTF8();  
     bytes = utf8.GetBytes(requestXml);  
     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);  
     request.set_ContentType("text/xml; encoding='utf-8'");  
     request.set_ContentLength(bytes.get_Length());  
     request.set_Method("POST");  
     request.set_Headers(httpHeader);  
     requestStream = request.GetRequestStream();  
     requestStream.Write(bytes, 0, bytes.get_Length());  
     response = request.GetResponse();  
     responseStream = response.GetResponseStream();  
     streamReader = new System.IO.StreamReader(responseStream);  
     responseXml = streamReader.ReadToEnd();  
     info(responseXml);  
   }  
   catch (Exception::CLRError)  
   {  
     //bp deviation documented  
     ex = CLRInterop::getLastException().GetBaseException();  
     error(ex.get_Message());  
   }  
   requestStream.Close();  
   streamReader.Close();  
   responseStream.Close();  
   response.Close();  
 }  
Thanks for reading the blog Happy daxing ?
发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址