1

We have a web service callout in Salesforce to a third party, that renders illegal content, which means that their web service returns a response that claims to be UTF-8 text, but isn't. When I base64 decode that text on my local pc, I can verify that the text is in fact ISO-8859-1 data.

However, EncodingUtil.base64Decode() crashes on this input, so it is impossible to decode it in Apex and then perform some conversion afterwards.

Is there any other way to handle this besides asking the third party to become compliant? It could be done in Heroku, but if possible, I'd like it to be done directly in Apex.

0
3

You can take the "long way around" by first converting to hex, then converting to URL-encoded form, and then finally to UTF-8 via ISO-8859-1 decoding.

// 'ááááá' in base64 in ISO-8859-1
Blob source = EncodingUtil.base64Decode('4eHh4eE='); 
String hexSource = EncodingUtil.convertToHex(source);
String urlEncoded = hexSource.replaceAll('(.{2})','%$1');
String recoveredText = EncodingUtil.urlDecode(urlEncoded,'iso-8859-1');
System.debug(recoveredText); // 'ááááá'

Or as a parameter chain:

String recoveredText = EncodingUtil.urlDecode(
    EncodingUtil.convertToHex(source) // source = original Blob
    .replaceAll('(.{2})','%$1'),
    'iso-8859-1'
);
8
  • Thanks, but I'm afraid this doesn't not work in our case, as the source is already corrupt, meaning that they supply an xml response that is ISO-8859-1, but the xml-header says <?xml version="1.0" encoding="UTF-8"?> That causes base64Decode to throw an exception – EdP May 20 at 8:09
  • @EdP The base64 decode in my example is only to get to a point where I have a Blob, which I presumed is where you were at. Your original response data should start out as a Blob, not text. In your HttpResponse, use getBodyAsBlob(), not getBody(). – sfdcfox May 20 at 11:59
  • Yes, I get it, but in our case the response is always a base64-encoded zip file (with corrupted content) within the xml text, so base64Decode is realy the very first thing to do. Thanks for your input though. I'm afraid Heroku might be the only way out, apart from the third party changing their response. – EdP May 21 at 8:27
  • @EdP A zip file isn't a "corrupted" text file, it's compressed data. You can use Zippex to decompress the content, and then parse it from there. – sfdcfox May 21 at 12:15
  • Thanks, actually, we do use Zippex, but it needs to be base64Decoded first and that is the thing that fails when a corrupt xml string is what is inside the base64 encoded string. So again, I'm afraid that Apex cannot help us out here, it seems that Salesforce's base64Decode does more than simply decoding its input, it does some checks as well. Decoding it in Heroku will not suffer from that same issue. – EdP May 25 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.