I'm trying to escape test+test@test.com email in salesforce REST query.


But it replaces + sign with space, before parsing a query. That results in error:

{ message: " Id FROM Contact WHERE Email LIKE 'test\ test@test.com' ^ ERROR at Row:1:Column:40 Invalid string literal 'test\ test@test.com'. Illegal character sequence '\ ' in string literal." errorCode: "MALFORMED_QUERY" }

Is it possible to escape + on url, so it's treated correctly when query parsed?


This is not the most elegant solution but I've encountered the same problem before, you're more than welcome to use this:

    strQuery = 'YOUR+QUERY+HERE';
    strQuery = strEndPoint.replace('%','%25');
    strQuery = strEndPoint.replace(' ','%20');
    strQuery = strEndPoint.replace('+','%2B');
    strQuery = strEndPoint.replace('\'','%27');

then add more escape character replacements as necessary depending on the characters you're using in your querystring.

After all that, just append strQuery to 'https://na16.salesforce.com/services/data/v32.0/query/?q='.


EncodingUtil.urlEncode() will do what you are looking for:

String stringToEncode = 'test+test@test.com';
String encodedUrl = EncodingUtil.urlEncode(stringToEncode, 'UTF-8');

The code above outputs:


You can use EncodingUtil.urlDecode() to get it back to its original form.

  • 1
    This. So much this. The correct tool for the job.
    – Mark Pond
    Jun 11 '15 at 16:16

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.