Escape Special Characters in Merge Fields for Apex Callouts That Use Named Credentials

Your code can use merge fields to construct the bodies of Apex callouts to named credential–defined endpoints. Those merge fields now support the HTMLENCODE function so you can escape special characters, such as underscore (_) and ampersand (&), in the merge fields in callout bodies.

HTMLENCODE is an existing formula function. Other formula functions aren’t supported, and you can’t use HTMLENCODE on merge fields in HTTP headers.

Example

The following example escapes special characters in credentials.
req.setBody('UserName:{!HTMLENCODE($Credential.Username)}')
req.setBody('Password:{!HTMLENCODE($Credential.Password)}')