Set the Content Type in Header for Apex REST POST Request

Jeff Douglas (as usual) has an excellent Apex POST request example at his blog. It demonstrates how to perform callouts during trigger execution. The example is missing one thing, however, that can be critical to the ability of the service being called to interpret your request body: the Content Type.

Depending on whether you are using the JSON or XML classes to encode your data, you will need to add the Content Type attribute to the header to indicate how the service being called should read the request body. Here is an example for passing a JSON object:
req.setHeader('Content-Type','application/json; charset=utf-8');

 

Posted in Learning