JSON in Dynamics AX – Advanced example #1 (Basic Auth)

11 11 2013

After my previous post on using JSON in Dynamics AX2012 I have received a number of requests for some slightly more advanced examples. I will attempt over the next couple of weeks to provide some.

Today I will cover the use of Basic http authentication. There are a couple of non-intuitive tricks that one needs to use to get it to work.
Before performing any direct requests as per our previous example you will need to make some modifications to the headers in your RetailRequestWeb object.

The first header modification is to add the “Authorization: Basic ” header. You can do so by building up the header string as follows

System.Text.Encoding ascii;
str credentials;
credentials = "myusername:mypassword";
//N.B. Encode the credentials before adding them to your headers otherwise you will receive 403 unauthorized errors
ascii = System.Text.Encoding::get_ASCII();
credentials = System.Convert::ToBase64String(ascii.GetBytes(credentials));
//Combine header instruction and encoded credentials
request.parmHeader("Authorization: Basic "+credentials);

The second modification you need to make is set the request content type to “application/json” without this you may receive 403 unauthorized errors. The retails API allows you to set the content type easily by using the parmContentType method on your RetailRequestWeb object.

request.parmContentType("application/json");

Finally the full example of constructing your json request ready for use:

RetailWebRequest request;
System.Text.Encoding ascii;
str credentials;

request = RetailWebRequest::newUrl(_url);
credentials = "myusername:mypassword";
ascii = System.Text.Encoding::get_ASCII();
credentials = System.Convert::ToBase64String(ascii.GetBytes(credentials));
request.parmHeader("Authorization: Basic "+credentials);
request.parmContentType("application/json");
Advertisements

Actions

Information

One response

12 11 2013
Timothy Solomon (@TimoSolo)

Interesting.. Thanks for sharing :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: