HTTP post/put requests

X++ code to make HTTP post/put requests to external services:
    protected str makeWebRequest(str _url, str _method, str _body, str _contentType)
    {
        System.Net.HttpWebRequest        webRequest;
        System.Net.HttpWebResponse      webResponse;
        System.IO.Stream                stream;
        System.IO.StreamReader          streamReader;
        System.Byte[]                   bytes;
        System.Net.WebHeaderCollection  headers;
        str                             response = '';
        System.Text.UTF8Encoding        encoding;

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

        webRequest = System.Net.WebRequest::Create(_url) as System.Net.HttpWebRequest;
        //Making header collection and setting the requisites
        headers = new System.Net.WebHeaderCollection();
        if (authToken)
        {
            headers.Add('Authorization: Bearer ' + authToken);
        }
        webRequest.set_Headers(headers);
        // PUT / POST
        webRequest.set_Method(_method);
        // webRequest.set_Accept('application/json');
        // application/x-www-form-urlencoded
        // application/json
        webRequest.set_ContentType(_contentType);
        webRequest.set_Timeout(5000);
        //setting encoding
        encoding    = new System.Text.UTF8Encoding();
        bytes       = encoding.GetBytes(_body);
        webRequest.set_ContentLength(bytes.get_Length());
        stream        = webRequest.GetRequestStream();
        stream.Write(bytes, 0, bytes.get_Length());
        stream.Close();
        try
        {
            webResponse         = webRequest.GetResponse();
            stream              = webResponse.GetResponseStream();
            streamReader        = new System.IO.StreamReader(stream);
            response            = streamReader.ReadToEnd();
            streamReader.Close();
            stream.Close();
        }
        catch (Exception::CLRError)
        {
            System.Exception        ex;
            System.Net.WebException webException;

            ex                = CLRInterop::getLastException().GetBaseException();
            webException    = ex as System.Net.WebException;
            webResponse        = webException.Response;
            if (webResponse)
            {
                stream              = webResponse.GetResponseStream();
                streamReader        = new System.IO.StreamReader(stream);
                response            = streamReader.ReadToEnd();
                streamReader.Close();
                stream.Close();
            }
        }
        CodeAccessPermission::revertAssert();

        return response;
    }


Search

About

DaxOnline.org is free platform that allows you to quickly store and reuse snippets, notes, articles related to Dynamics AX.

Authors are allowed to set their own AdSense units.
Join us.

Blog Tags