8

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?

  • you are getting the login page because your missing the access cookie – Ryan Guest Nov 1 '13 at 4:19
9

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.

2

If you're just looking to get the content of the VisualForce page you can use the PageReference getContent() instance method (docs). Looking at the docs it's available for use in callouts.

You can call internal URLs as well as Salesforce APIs from within APEX but it's not easy and not supported. I haven't done this myself, but I believe setting a cookie with the current user's session id would be sufficient. Of course Salesforce doesn't give full access to headers or cookies, so you might run into issues. One example of consuming a Salesforce SOAP API is the APEX Metadata API Wrapper by @AndrewFawcett. It has loads of interesting techniques and discussion in the readme.

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.