web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

Consume a webservice REST in AX 2009

(0) ShareShare
ReportReport
Posted on by 50

Hello, 

I would like consume a webservice REST in AX2009 to track the shipment of our orders. 

For this I used this example : Consuming REST APIs in Dynamics AX 2012 (folio3.com)

I modified for my case like this :

 

static void Job37(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();

   ;

   //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://api.dachser.com/rest/v2/shipmenthistory?tracking-number=4619790347927552&customer-id=231993665126400");

    webReq = clrObj;

    //Set Method Type

    webReq.set_Method("GET");

    webReq.set_KeepAlive(true);

    // Set Content type

    webReq.set_ContentType("application/xml");

    // Add Authorization code

    //headers.Add("Authorization", "sdfgvczzxcbtyfrvb");
    headers.Add("X-IBM-Client-Id", "clientId");
    headers.Add("Accept-Language", "en");
    headers.Add("accept", "application/json");

    //Add header to request

    webReq.set_Headers(headers);

    //Get Service Point

    servicePt = webReq.get_ServicePoint();

    servicePt.set_Expect100Continue(false);

    //Gets the response object

    webRes = webReq.GetResponse();

    //Get Stream

    stream = webRes.GetResponseStream();

    streamRead = new System.IO.StreamReader(stream);

    stream.Close();

    webRes.Close();

}

But the code exits on "webReq.set_Headers(headers);" line. 

I don't know why. Please could you help me ? 

Thanks a lot. 

I have the same question (0)
  • Suggested answer
    ergun sahin Profile Picture
    8,826 Moderator on at

    set headers at the top (before other settings)

  • mimi51340 Profile Picture
    50 on at

    Hello,

    It seems to work but now I exit without message at :

    webRes = webReq.GetResponse();

    Any idea ? 

    Thanks. 

  • Suggested answer
    ergun sahin Profile Picture
    8,826 Moderator on at

    I don't see any obvious errors. You can try your luck with try/catch (If you can get error it will a lot easier)

  • mimi51340 Profile Picture
    50 on at

    Like below ? I don't get any message...

    static void Job37(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();
    
       ;
    
        try
        {
           //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://api.dachser.com/rest/v2/shipmenthistory?tracking-number=4619790347927552&customer-id=231993665126400");
    
            webReq = clrObj;
    
            //Set Method Type
    
            webReq.set_Method("GET");
    
            webReq.set_KeepAlive(true);
    
            // Set Content type
    
            webReq.set_ContentType("application/xml");
    
            //Add header to request
            webReq.set_Headers(headers);
            // Add Authorization code
    
            //headers.Add("Authorization", "sdfgvczzxcbtyfrvb");
            headers.Add("X-IBM-Client-Id", "clientId");
            headers.Add("Accept-Language", "en");
            headers.Add("accept", "application/json");
    
    
    
    
            //Get Service Point
    
            servicePt = webReq.get_ServicePoint();
    
            servicePt.set_Expect100Continue(false);
    
            //Gets the response object
    
            webRes = webReq.GetResponse();
    
            //Get Stream
    
            stream = webRes.GetResponseStream();
    
            streamRead = new System.IO.StreamReader(stream);
    
            stream.Close();
    
            webRes.Close();
        }
        catch (Exception::Error)
        {
            info("Caught 'Exception::Error'.");
            throw Exception::Error;
        }
    
    }

  • Verified answer
    ergun sahin Profile Picture
    8,826 Moderator on at

    Nope You need catch CLRError.

    catch (Exception::CLRError)
    {
        throw error(AifUtil::getClrErrorMessage());
    }
    ---------OR----------
    catch(Exception::CLRError)
    {
        ex = CLRInterop::getLastException();//ex-->System.Exception ex;
        info(ex.ToString());
    }

    Or if you have inner exception

    catch(Exception::CLRError)
    {
        exc = CLRInterop::getLastException();
        if( exc )
        {
            clrExcMessage = exc.get_Message();
            // BP Deviation Documented
            strError = CLRInterop::getAnyTypeForObject( clrExcMessage );
    
            innerExc = exc.get_InnerException();
            while(innerExc != null)
            {
                clrExcMessage = innerExc.get_Message();
                // BP Deviation Documented
                strError = strError   '\n'   CLRInterop::getAnyTypeForObject( clrExcMessage );
                innerExc = innerExc.get_InnerException();
            }
        }
    }

    Note: Right now I don't have a chance to check from ax 2009. I found this examples , on the internet after a few minutes of searching. But if you search for "catch" in system classes, you can find much more accurate examples.

  • mimi51340 Profile Picture
    50 on at

    Hello,

    Thanks for your help.

    Now I get an error :

    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Net.WebException: The underlying connection has been closed : An unexpected error occurred on a send. ---> System.IO.IOException: Received an unexpected EOF or 0 bytes from the transport stream.
       à System.Net.FixedSizeReader.ReadPacket(Byte[] buffer, Int32 offset, Int32 count)
       à System.Net.Security.SslState.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
       à System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
       à System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
       à System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
       à System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)
       à System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)
       à System.Net.TlsStream.CallProcessAuthentication(Object state)
       à System.Threading.ExecutionContext.runTryCode(Object userData)
       à System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
       à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
       à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       à System.Net.TlsStream.ProcessAuthentication(LazyAsyncResult result)
       à System.Net.TlsStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       à System.Net.PooledStream.Write(Byte[] buffer, Int32 offset, Int32 size)
       à System.Net.ConnectStream.WriteHeaders(Boolean async)
       --- Fin de la trace de la pile d'exception interne ---
       à System.Net.HttpWebRequest.GetResponse()
       --- Fin de la trace de la pile d'exception interne ---
       à System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       à System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
       à System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
       à System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       à ClrBridgeImpl.InvokeClrInstanceMethod(ClrBridgeImpl* , ObjectWrapper* objectWrapper, Char* pszMethodName, Int32 argsLength, ObjectWrapper** arguments, Boolean* argsAreByRef, Boolean* isException)

    Could you help me please ? I get the error on this line : webRes = webReq.GetResponse();

    I tried directly on the API portal of the partner, The correct URL is for example :

    clrObj = System.Net.WebRequest::Create("https://api.dachser.com/rest/v2/shipmenthistory?tracking-number=4572418880307200&customer-id=8305600968523776");

    And headers : 

            headers.Add("Accept-Language", "application/json");
            headers.Add("X-IBM-Client-Id", "ce4fcc672e2f154342e318e1fa674c78");
            headers.Add("accept", "application/json");

    Thank you very much. 

  • Suggested answer
    ergun sahin Profile Picture
    8,826 Moderator on at

    Can you check service's TLS/SSL version (Security Protocol Type)

  • mimi51340 Profile Picture
    50 on at

    Where can I see it ? In AX ?

  • Suggested answer
    ergun sahin Profile Picture
    8,826 Moderator on at

    You can find it using Web Browser. I checked it I think it's using tls 1.2.

    Ax 2009 uses .Net framework 3.5. In the past, tls 1.2 was not used with this version. Later, this situation changed, but as far as I know, there was no change in the ax kernel (You can't see 1.2 among the types)

    This has multiple solutions. I shared a solution I came across below but actually there was a simpler solution I was looking for.

    community.dynamics.com/.../dutch-taxreport-must-be-send-with-new-certificates-and-tls-1-2 109373=1#responses

  • mimi51340 Profile Picture
    50 on at

    Thanks, so I created a file ax32.exe.conf from client side.

    I executed the job "TLS_check" and I get : TLS security level TLS 1.2 is allowed by AX.

    But now in my program, I get another error, do you think I have forgotten something ? 

    System.Reflection.TargetInvocationException: An exception has been thrown by the target of an invocation. ---> System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
       à System.Net.HttpWebRequest.GetResponse()
       --- Fin de la trace de la pile d'exception interne ---
       à System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       à System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
       à System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       à ClrBridgeImpl.InvokeClrInstanceMethod(ClrBridgeImpl* , ObjectWrapper* objectWrapper, Char* pszMethodName, Int32 argsLength, ObjectWrapper** arguments, Boolean* argsAreByRef, Boolean* isException)

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Finance | Project Operations, Human Resources, AX, GP, SL

#1
Martin Dráb Profile Picture

Martin Dráb 646 Most Valuable Professional

#2
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 529 Super User 2025 Season 2

#3
Sohaib Cheema Profile Picture

Sohaib Cheema 285 User Group Leader

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans