0

I am getting

Session invalid or session expires

error when i am calling one Saleforce org from another Salesforce org. here my code for callout.

String content = '{"Name": "Some acoount", "Phone":"9742882954"}';
 HttpRequest req = new HttpRequest();
 req.setEndpoint('https://ap1.salesforce.com/services/apexrest/Accountacc');
 req.setMethod('POST');

 String username = 'sarvesh01@gmail.com';
 String password = 'parvati@3';

 Blob headerValue = Blob.valueOf(username + ':' + password);
 String authorizationHeader = 'BASIC ' +
 EncodingUtil.base64Encode(headerValue);
 req.SetBody(content);
 req.setHeader('Content-Type', 'application/json; charset=utf-8');
 req.setHeader('Authorization', authorizationHeader);
 req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());    
 Http http = new Http();
 HTTPResponse res = http.send(req);
 System.debug(res.getBody());

my rest class in another salesforce org.

@RestResource(urlMapping='/Accountacc/*')  
global with sharing class callAccount {  

@HttpPost  
 global static String doPost() {  

 RestRequest request = RestContext.request;  
 RestResponse response = RestContext.response;  
 String jSONRequestBody=request.requestBody.toString().trim();  
 Account accObj = (Account)JSON.deserializeStrict(jSONRequestBody,Account.class);  
 insert accObj;  
 return accObj.Id;  
}  
@HttpGet  
global static Account doGet() {  

 RestRequest request = RestContext.request;  
 RestResponse response = RestContext.response;  
 String accountId = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);  
 Account acc= [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];  
 return acc;  
}  
}

Can any one help me out please........ Thanks, sarvesh.

1
  • Can you try with authorization type 'Bearer' instead of 'OAuth? – Torsen Nov 2 '15 at 10:36
0

Salesforce does not support basic authentication for REST calls.

Probably the most appropriate authentication to use is OAuth 2.0 JWT Bearer Token Flow where a certificate is used to secure the Salesforce to Salesforce access. See An Apex implementation of the OAuth 2.0 JWT Bearer Token Flow for how to make the request in Apex.

Once the access token is obtained it can be used to authenticate the REST requests:

HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'OAuth ' + accessToken);
...
2
  • Hi Keith C, Thanks for your replay but can you give example for salesforce rest callout – sarvesh Nov 2 '15 at 10:02
  • @sarvesh Added to the answer. – Keith C Nov 2 '15 at 10:20

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.