HTTP post/put requests

X++ code to make HTTP post/put requests to external services:
class VKWebRequest
{
    #Define.HTTPCodeAuthErr(401)
    str		authToken;
    str		basicAuthUserName;
    str		basicAuthPassword;
    int		timeout;
    int		statusCode;

    protected void new()
    {
        timeout = 180000; // 3 min
    }

    public str parmAuthToken(str _authToken = authToken)
    {
        authToken = _authToken;
        return authToken;
    }

    public str parmBasicAuthUserName(str _username = basicAuthUserName)
    {
        basicAuthUserName = _username;
        return basicAuthUserName;
    }

    public str parmBasicAuthPassword(str _password = basicAuthPassword)
    {
        basicAuthPassword = _password;
        return basicAuthPassword;
    }

    public int getStatusCode()
    {
        return statusCode;
    }

    public boolean isAuthenticationError()
    {
        return (statusCode == #HTTPCodeAuthErr) ? true : false;
    }

	/// <summary>
    /// In milliseconds 1000 = 1 sec, default value 180 000
    /// </summary>
    /// <param name = "_timeout">milliseconds</param>
    /// <returns></returns>
    public int parmTimeout(int _timeout = timeout)
    {
        timeout = _timeout;
        return timeout;
    }

    public static VKWebRequest construct()
    {
        return new VKWebRequest();
    }

    public boolean getAuthorizationToken(str _url, str _userName, str _password)
    {
        boolean					ret = true;

        #define.AccessToken('access_token')
        #define.ErrorDescription('error_description')

        str authBody = strFmt('client_id=pat&grant_type=password&username=%1&password=%2', _userName, _password);

        str			response = '';
        container	value;
        response = this.makeWebRequest(_url, 'POST', authBody, 'application/x-www-form-urlencoded');

        if (response)
        {
            Map	responseMap = RetailCommonWebAPI::getMapFromJsonString(response);
            if (responseMap.exists(#AccessToken))
            {
                value		= responseMap.lookup(#AccessToken);
                authToken	= conPeek(value, 1);
            }
            if (responseMap.exists(#ErrorDescription))
            {
                value	= responseMap.lookup(#ErrorDescription);
                ret		= false;
                Error(conPeek(value, 1));
            }
        }

        if (!authToken)
        {
            ret = false;
        }
        return ret;
    }

    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);
        }
        else if (basicAuthUserName && basicAuthPassword)
        {
            System.Text.Encoding authEncoding = System.Text.Encoding::UTF8;
            System.Byte[] authBytes = authEncoding.GetBytes(basicAuthUserName + ':' + basicAuthPassword);
            System.String base64 = System.Convert::ToBase64String(authBytes);
            headers.Add('Authorization: Basic ' + base64);
        }
        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(timeout);
        //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();
            }
        }
        if (webResponse)
        {
            statusCode = webResponse.StatusCode;
        }
        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