1

I'm trying to pass the given URL to the setEndpoint method, but I'm getting an error.

This particular API URL contains backslash and maybe that's the problem because the code works fine with other URLs which don't have backslashes.

Please let me know how do we encode/decode this to pass it as an argument.

 HttpRequest req = new HttpRequest();

 String url='https://api.example.com/s1/output?filter\[abc\]\[\]=xyz';

 req.setEndpoint(url);

Also, this URL works completely fine with the curl command!

4

I strongly suspect that something is going sideways because you're not properly escaping the non-safe URL characters (like \ and [); in a URL, they must be in a certain style known as "percent encoding". Here's how I'd approach your problem:

ApexPages.PageReference ref = new ApexPages.PageReference('https://api.example.com/output');
ref.getParameters().put('filter\\[abc\\]\\[\\]', 'xyz');
String theUrl = ref.getUrl();
req.setEndpoint(theUrl);

This produces output like:

https://api.example.com/output?filter%5C%5Babc%5C%5D%5C%5B%5C%5D=xyz

Things like "curl" are smart enough to do this for you, but in Salesforce, you always need to use either EncodingUtils.urlEncode or PageReference.

Edit: The URL doesn't have backslashes in it; the backslashes that were used are required by the shell for curl to properly detect the brackets. So, simply removing those should fix the issue:

ApexPages.PageReference ref = new ApexPages.PageReference('https://api.example.com/output');
ref.getParameters().put('filter[abc][]', 'xyz');
String theUrl = ref.getUrl();
req.setEndpoint(theUrl);
  • @SnehaJagtap There's no backslashes in that URL. Perhaps that is the problem? – sfdcfox Jun 29 '18 at 18:52
  • no clue why backslashes aren't showing up here! Trying again - "api.example.com/s1/output?filter[abc][]=xyz" – Sneha Jagtap Jun 29 '18 at 18:56
  • I have edited the url in the question. That's the exact URL! So sorry for inconvenience :) – Sneha Jagtap Jun 29 '18 at 18:57
  • @SnehaJagtap No, I think you're misunderstanding. I don't think the URL needs it; the backslashes are to escape the [ and ] in the shell, so they're needed for curl, but not for the server you're calling. Please read my edited version and give it a try. – sfdcfox Jun 29 '18 at 18:59

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.