HTTP post/put requests

X++ code to make HTTP post/put requests to external services:
/// <summary>
/// Makes various HTTP(s) requests with related processing.
/// </summary>
class VKWebRequest
{
    #Define.HTTPCodeAuthErr(401)
    #Define.HTTPCodeOK(200)
    #Define.HTTPCodeCreated(201)
    #Define.HTTPCodeAccepted(202)
    str     authToken;
    str     basicAuthUserName;
    str     basicAuthPassword;
    int     timeout;
    int     statusCode;
 
    protected void new()
    {
        timeout = 180000; // 3 min
    }

    /// <summary>
    /// To use with Authorization: Bearer {Token}
    /// </summary>
    /// <param name = "_authToken">Authorization token</param>
    /// <returns>Authorization token</returns>
    public str parmAuthToken(str _authToken = authToken)
    {
        authToken = _authToken;
        return authToken;
    }

    /// <summary>
    /// Username to use together with Basic Authorization.
    /// </summary>
    /// <param name = "_username">Username</param>
    /// <returns>Username</returns>
    public str parmBasicAuthUserName(str _username = basicAuthUserName)
    {
        basicAuthUserName = _username;
        return basicAuthUserName;
    }

    /// <summary>
    /// Password to use together with Basic Authorization.
    /// </summary>
    /// <param name = "_password">Password</param>
    /// <returns>Password</returns>
    public str parmBasicAuthPassword(str _password = basicAuthPassword)
    {
        basicAuthPassword = _password;
        return basicAuthPassword;
    }

    /// <summary>
    /// Gets HTTP status code
    /// </summary>
    /// <returns>int</returns>
    public int getStatusCode()
    {
        return statusCode;
    }

    /// <summary>
    /// Indicates if there was authentication error or not.
    /// </summary>
    /// <returns>boolean</returns>
    public boolean isAuthenticationError()
    {
        return (statusCode == #HTTPCodeAuthErr) ? true : false;
    }

    /// <summary>
    /// Indicates that HTTP status code is 200 (sucessfully processed).
    /// </summary>
    /// <returns>Boolean</returns>
    public boolean isHttpStatusCodeOK()
    {
       return (statusCode == #HTTPCodeOK || statusCode == #HTTPCodeCreated || statusCode == #HTTPCodeAccepted) ? true : false;
    }

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

    /// <summary>
    /// Constructor
    /// </summary>
    /// <returns>VKWebRequest</returns>
    public static VKWebRequest construct()
    {
        return new VKWebRequest();
    }

    /// <summary>
    /// Request to get quthorization token bearer.
    /// Authorization token stored in the variable and can be fetched using param method if required.
    /// </summary>
    /// <param name = "_url">URL</param>
    /// <param name = "_userName">Username</param>
    /// <param name = "_password">Password</param>
    /// <returns>boolean</returns>
    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;
    }

    /// <summary>
    /// Executes request to a web page / service
    /// </summary>
    /// <param name = "_url">URL</param>
    /// <param name = "_method">Method: POST/GET/PUT ...</param>
    /// <param name = "_body">Body of request</param>
    /// <param name = "_contentType">Content type</param>
    /// <returns>response</returns>
    public 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 and "buy me a coffee" link.
Join us.

Blog Tags