I'm trying to escape [email protected] email in salesforce REST query.

https://na16.salesforce.com/services/data/v32.0/query/?q=SELECT+Id+FROM+Contact+WHERE+Email='[email protected]'

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

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

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

2 Answers 2


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 = '[email protected]';
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, 2015 at 16:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .