3

I'm developing an application where my code will make a Http POST request to a web service lying in my org.

As of now, this is what I'm doing:

HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();

req.setEndpoint(Constants.SF_BASE_URL + '/services/apexrest/peer/v2/loanAccounts/setupACH/' + (String)contract.get('Id')); // http://ap4.salesforce.com/......
req.setMethod('POST');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId());

Map<String, String> urlParams = new Map<String, String>();
urlParams.put(..., ...); // about 10 of these of these

System.PageReference pageReference = new System.PageReference('');
pageReference.getParameters().putAll(urlParams);
String query = pageReference.getUrl().substringAfter('?'); // to get the url encoded query

req.setBody(query);
req.setTimeout(20000);

res = http.send(req);

I figured out how to do this after many painful hours of searching the web. Everyone tells you how to create a web service, but no one will tell you how to call it, especially from salesforce.

Anyway, when I try and run this code, I get an error saying

Unauthorized endpoint, please check Setup->Security->Remote site settings. endpoint = https://ap4.salesforce.com/services/apexrest/peer/v2/loanAccounts/setupACH/a6E6F00000001nrUAA

I can't create a Remote Site Settings entry because the URL is likely to change as my code could run on different instances.

Is there any alternative way I can make this happen?

1 Answer 1

2

The address you need to whitelist in your Remote Site Settings is just the instance:

https://ap4.salesforce.com

Once you whitelist that, internal API calls should work just fine.

7
  • That's good news! Can I do this via code? Preferably some code to check for an entry before actually making the callout. I don't want someone to manually do it every time the instance changes.
    – coldspeed
    Apr 18, 2017 at 19:51
  • Do your instances change often? You'd have to resort to Javascript if you want to go the code route, as any Apex callouts depend on the instance itself already being whitelisted.
    – Adrian Larson
    Apr 18, 2017 at 19:52
  • No but my code is going to possibly reside on different instances. Plus when testing we test in different orgs, so the instance and/or the base URL could be different.
    – coldspeed
    Apr 18, 2017 at 19:53
  • See also: salesforce.stackexchange.com/a/169382/2995
    – Adrian Larson
    Apr 18, 2017 at 19:53
  • Alright, one last thing. Is there an alternative way to make the WS call without whitelisting or tooling?
    – coldspeed
    Apr 18, 2017 at 19:55

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.