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?