3

I am facing following issue: On load of visualforce page I am making http callout to internal salesforce page but here I facing authentication problem.

If I am running same http callout from developer console then I am getting successful response but that same code is not working with visualforce page. Reason for not working is my session id in developer console and visualforce domain is different.

For fetching session id I am using "UserInfo.getSessionId()"

I have also tried {!$Api.Session_ID} but not working

My controller:

public with sharing class HttpRequestForPage
{
   public HttpRequestForPage()
   {
       requestForPage('https://ap1.salesforce.com/home/home.jsp');
   }
   public void requestForPage(String pageUrl)
    { 
        HttpResponse responseOfPage;
        String responseString;
        HttpRequest request = new HttpRequest();
        request.setMethod('GET'); 
        request.setEndpoint('https://ap1.salesforce.com/home/home.jsp');
        request.setHeader('Cookie', 'sid='+UserInfo.getSessionId());

        try
        {
            responseOfPage = new Http().send(request);
        }
        catch(Exception e)
        {
            system.debug(e);
        }
        responseString = responseOfPage.getBody();
        System.debug(responseString=='+responseString);

    }
}
user3682511
  • 45
  • 1
  • 7

1 Answers1

0

Rather than setting a cookie for the session try using the authorization header.

request.setHeader('Authorization','Bearer '+UserInfo.getSessionId());

You will also need to set ap1.salesforce.com as an endpoint in the remote site settings.


If you are requesting pages from within Salesforce you can just use the PageReference getContent() method.

PageReference home = new PageReference('https://ap1.salesforce.com/home/home.jsp');
blob homeblob = home.getContent();
string homeContent = homeblob.toString();
Daniel Ballinger
  • 13,187
  • 11
  • 69
  • 96