[SalesForce] Web Service Callout exception: Invalid Session Id

public class webServicesTriggerClass
{
  @future(callout = true)
   public static void webServicesMethod(list<ID> Id1)
   {   
   partnerSoapSforceCom.Soap sp = new partnerSoapSforceCom.Soap(); 
   partnerSoapSforceCom.LoginResult lr = sp.login('****','****');
   soapSforceComSchemasClassNiralaapp.SessionHeader_element ses = new soapSforceComSchemasClassNiralaapp.SessionHeader_element();
    system.debug('################################' +ses.sessionId);
    ses.sessionId = lr.sessionId; 
   system.debug('################################' +ses.sessionId);   
   soapSforceComSchemasClassNiralaapp.MyFriendsDetailSoapApi vNapp=new soapSforceComSchemasClassNiralaapp.MyFriendsDetailSoapApi();
   list<MyFriend__c> mfList=new list<MyFriend__c>([select id,myEmail__c,friendName__c,friendEmail__c,aboutFriend__c ,age__c from MyFriend__c where id in:id1]);
     for(MyFriend__c mf:mfList)
      {
     string  s1= mf.myEmail__c;
     string  s2=mf.friendName__c;
     string  s3=mf.friendEmail__c;
     string  s4=mf.aboutFriend__c;
     integer i1=Integer.ValueOf(mf.age__c);
     boolean result=vNapp.addFriendDetails(s1,s2,s3,s4,i1);
     system.debug('################################' +result);    
      }
   }
}

Trigger–

trigger webServicesTrigger on MyFriend__c (after insert) 
 {
    list<ID> Ids=new list<ID>();
    for(MyFriend__c mYFR:Trigger.new)
     {
       Ids.add(mYFR.Id);
     }
     webServicesTriggerClass.webServicesMethod(Ids);
 }

When I am executing this code, I am getting this error-

System.CalloutException: Web service callout failed: WebService
returned a SOAP Fault: INVALID_SESSION_ID: Invalid Session ID found in
SessionHeader: Illegal Session faultcode=sf:INVALID_SESSION_ID
faultactor=

Best Answer

pluto,

just like you take the sessionId from loginResult and set it to sessionHeader, you need to take the serverURL from loginResult and assign it to the api object endpoint URL.. and the sessionHeader you initialized is not being assigned to the actual callout object.

vNapp.SessionHeader = ses;
vNapp.URL = lr.serverURL;