[SalesForce] Making a Http GET callout to internal Salesforce URL

I have a Salesforce VisualForce page that pretty much just Outputs XML:

https://[mynameserver]/Apex/[myxmlpage]

I want to expose a WSDL service where I am pretty much just going to wrap the contents of this page. In order to do so, I figured the quickest/cheapest method to do so would just be to make an internal HTTP GET request to this the visual force page and then return the content in the service.

Http h = new Http();
HttpRequest webReq = new HttpRequest();
webReq.setMethod('GET');
webReq.setEndpoint('https://[mynameserver]/Apex/[myxmlpage]');
HttpResponse res = h.send(webReq);
System.debug(res.getbody());

Unfortunately when I try this I get redirected to the login screen. I guess I need to add authorization to the HTTP Callout.

Has anyone ever done this and have more details on the best/easiest way to make this happen?

Best Answer

If you have requirement of call-out to internal Salesforce url from logged in session, Use your code as:

Http h = new Http();
HttpRequest webReq = new HttpRequest();
webReq.setMethod('GET');
webReq.setHeader('Authorization','Bearer '+UserInfo.getSessionId());
// replace endpoint url
webReq.setEndpoint('https://na12.salesforce.com/udd/Site/siteDashboard.apexp');
HttpResponse res = h.send(webReq);
System.debug(' ------ '+res.getbody());

Basically request need to be authorized. That is why you were redirected to login page. I assume that you have already added endpoint url in remote site setting of organization.

Related Topic