Thursday, July 6, 2017

Encoding and Decoding Data in Salesforce

EncodingUtil class in apex provides ability to encode and decode URL strings, and convert strings to hexadecimal format. 

Common use case can be like you want to store password of third party application which can be used while performing callout. So instead of storing the password, store encode format of password and and decode it while performing callout. Below is sample code which uses EncodingUtil methods to encode string and then decoding it back to string.

String password = 'Password123';
system.debug('******password' + password);
system.debug('******password Blob' + blob.valueof(password));
String encodedPassword = EncodingUtil.base64Encode(blob.valueof(password));
system.debug('********encodedPassword:' + encodedPassword);
blob decodedPasswordBlob = EncodingUtil.base64Decode(encodedPassword);
system.debug('********decodedPassword Blob:' + decodedPasswordBlob);
system.debug('********decodedPassword:' + decodedPasswordBlob.tostring());











Suppose you have to pass some parameters while performing callout, then you can encode your url parameters.
For example you have to send timestamp in url in yyyy-MM-dd'T'HH:mm:ss.SSS'Z' format. Below is sample code.

DateTime d = System.now();
String timestamp = ''+ d.year() + '-' +
d.month() + '-' +
d.day() + '\'T\'' +
d.hour() + ':' +
d.minute() + ':' +
d.second() + '.' +
d.millisecond() + '\'Z\'';
     
system.debug('********timestamp:'+timestamp);
String urlEncodedTimestamp = EncodingUtil.urlEncode(timestamp, 'UTF-8');
system.debug('********urlEncodedTimestamp:'+urlEncodedTimestamp);
//then you can append it to URL parameters. You can use below method to decode URL encoded strings.
String urlDecodedTimestamp = EncodingUtil.urlDecode(urlEncodedTimestamp, 'UTF-8');
system.debug('********urlDecodedTimestamp:'+urlDecodedTimestamp);




No comments:

Post a Comment