Gotcha! Using HttpContent in AL

I have been spending some time with Business Central, trying to get familiar with the usage of HttpClient and its related objects. That's when I ran across this little issue.

I was trying to put custom content in to a HttpClient post action.
Long story short, I ended up with this codeline:

myHttpContent.WriteFrom(myText);

And that gave me this error message at runtime:

The server cannot service the request because the media type is unsupported.

After a bit of searching around, I conclude that something like the following should do the trick:

myHttpContent.WriteFrom(myText);
myHttpHeaders.Add('Content-Type', 'text/xml');

I ran it and got the following run time error:

Misused header name. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects.

This was getting unusual!
So I bumble around and came up with the following code:

// the order of the following lines should not be changed
myHttpContent.WriteFrom(myText);
myHttpContent.GetHeaders(myHttpHeaders);
       
if myHttpHeaders.Contains('Content-Type') then
    myHttpHeaders.Remove('Content-Type');

myHttpHeaders.Add('Content-Type', 'text/xml');

This works!
Now I hope this will save someone, some of the time I wasted figuring it out.

Comments