You need to sign in to do that
Don't have an account?
❤Code
dynamically get session id rest api
Hi All,
I am trying to connect one sf org to anaother. I am using the below class to initiate the call from command button. I copied session id of target org and hard coded here in the class which then worked. But for next time it expires and i get invalid session id.
Can anyone help me out how i can dynamically have the session id of source org, so that i need not to hard code it.
public class Apex_Rest_DemoController {
public String response{get;set;}
public String accName{get;set;}
public String accPhone{get;set;}
public String accWebsite{get;set;}
public PageReference CreateAccount() {
//find access token using Auth 2.0
String Access_Token = '00D28000000Heme!AQ8AQAFOnSjXlGvbNT9JXj5vcC2XjQyFtz8ls_x0IMmoDuX91WDLvb9j5qficiTwQpCGjTYIRCUOmvwQOlWvP2.0HPA3x9M.';
Httprequest req=new httprequest();
String domainName='ap2.salesforce.com';
String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
req.setendpoint(endPointURL);
req.setHeader('Content-Type', 'application/xml; charset=utf-8');
req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
req.setmethod('POST');
req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
//req.setHeader('Authorization','Bearer '+Access_Token);
//req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
Http http = new Http();
HTTPResponse res = http.send(req);
response=res.getbody();
System.debug('****************res.getStatusCode();'+res.getStatusCode());
System.debug('****************res.getbody();'+res.getbody());
return null;
}
}
Regards
I am trying to connect one sf org to anaother. I am using the below class to initiate the call from command button. I copied session id of target org and hard coded here in the class which then worked. But for next time it expires and i get invalid session id.
Can anyone help me out how i can dynamically have the session id of source org, so that i need not to hard code it.
public class Apex_Rest_DemoController {
public String response{get;set;}
public String accName{get;set;}
public String accPhone{get;set;}
public String accWebsite{get;set;}
public PageReference CreateAccount() {
//find access token using Auth 2.0
String Access_Token = '00D28000000Heme!AQ8AQAFOnSjXlGvbNT9JXj5vcC2XjQyFtz8ls_x0IMmoDuX91WDLvb9j5qficiTwQpCGjTYIRCUOmvwQOlWvP2.0HPA3x9M.';
Httprequest req=new httprequest();
String domainName='ap2.salesforce.com';
String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
req.setendpoint(endPointURL);
req.setHeader('Content-Type', 'application/xml; charset=utf-8');
req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
req.setmethod('POST');
req.setHeader('Authorization','Authorization: Bearer '+Access_Token);
//req.setHeader('Authorization','Bearer '+Access_Token);
//req.setHeader('Authorization', 'OAuth '+UserInfo.getSessionId());
Http http = new Http();
HTTPResponse res = http.send(req);
response=res.getbody();
System.debug('****************res.getStatusCode();'+res.getStatusCode());
System.debug('****************res.getbody();'+res.getbody());
return null;
}
}
Regards
String Access_Token = UserInfo.getSessionId();
You need to make a call for access token instead of har coding it which can be in following format. as a response you will get access token that you can use in the above code.
Http h = new Http();
String body='grant_type='+password+'&client_id='+CLIENT_ID+'&client_secret='+CLIENT_SECRET+'&username=username&password=password+securitytoken';
HttpRequest req = new HttpRequest();
req.setEndpoint('https://login.salesforce.com/services/oauth2/token');
req.setMethod('POST');
req.setBody(body);
HttpResponse res = h.send(req);
Thanks
I want sessionid of traget org..i want to get connected to target sfdc org from source sfdc org. for that i need to have sessionid of target org. Could you please help me in that.
Regards
Grant_type = +password+. Is it password of my target org i have to give.
Regards
One option is to make a SOAP call using either the enterprise wsdl or the partner wsdl of the target environment and call the login method that takes the username & password+securityToken and get the sessionId as reponse.
Regards,
Anyway to acomplish this using rest api. The only point i am stuck is how to get the session id of my target sfdc org without hardcoding.
Reagrds
Regards
I got ur point. I will try this and let u know .
Regards
I modified my code .. Still getting invalid session id. Can u please check , what i am missing -
public class Apex_Rest_DemoController {
public String response{get;set;}
public String accName{get;set;}
public String accPhone{get;set;}
public String accWebsite{get;set;}
String LOGIN_DOMAIN = 'ap2';
public String pwd = '###############################';
public String userName = '########.########@###.com';
public PageReference CreateAccount() {
HttpRequest request = new HttpRequest();
request.setEndpoint('https://' + LOGIN_DOMAIN + '.salesforce.com/services/Soap/u/22.0');
request.setMethod('POST');
request.setHeader('Content-Type', 'text/xml;charset=UTF-8');
request.setHeader('SOAPAction', '""');
request.setBody('<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/"><Header/><Body><login xmlns="urn:partner.soap.sforce.com"><username>' + userName+ '</username><password>' + pwd+ '</password></login></Body></Envelope>');
Dom.XmlNode resultElmt = (new Http()).send(request).getBodyDocument().getRootElement()
.getChildElement('Body', 'http://schemas.xmlsoap.org/soap/envelope/')
.getChildElement('loginResponse', 'urn:partner.soap.sforce.com')
.getChildElement('result', 'urn:partner.soap.sforce.com');
final String SERVER_URL = resultElmt.getChildElement('serverUrl', 'urn:partner.soap.sforce.com') .getText().split('/services')[0];
final String SESSION_ID = resultElmt.getChildElement('sessionId', 'urn:partner.soap.sforce.com') .getText();
system.debug('@@@@@@' + SESSION_ID);
Httprequest req=new httprequest();
String domainName='ap2.salesforce.com';
String endPointURL='https://'+domainName+'/services/data/v34.0/sobjects/Account';
req.setendpoint(endPointURL);
req.setHeader('Content-Type', 'application/xml; charset=utf-8');
req.setBody('<?xml version="1.0" encoding="UTF-8" ?><request><name>'+accName+'</name><phone>'+accPhone+'</phone><website >'+accWebsite+'</website > </request>');
req.setmethod('POST');
request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
Http http = new Http();
HTTPResponse res = http.send(req);
response=res.getbody();
return null;
}
}
Regards
03:30:42.094 (94207002)|SYSTEM_METHOD_ENTRY|[20]|System.Http.send(ANY) 03:30:42.094 (94270318)|CALLOUT_REQUEST|[20]|System.HttpRequest[Endpoint=https://ap2.salesforce.com/services/Soap/u/34.0, Method=POST] 03:30:42.343 (343169950)|CALLOUT_RESPONSE|[20]|System.HttpResponse[Status=OK, StatusCode=200] 03:30:42.343 (343206569)|SYSTEM_METHOD_EXIT|[20]|System.Http.send(ANY) 03:30:42.343 (343235748)|SYSTEM_METHOD_ENTRY|[20]|System.HttpResponse.getBodyDocument() 03:30:42.343 (343462405)|SYSTEM_METHOD_EXIT|[20]|System.HttpResponse.getBodyDocument() 03:30:42.343 (343480410)|SYSTEM_METHOD_ENTRY|[20]|dom.Document.getRootElement() 03:30:42.343 (343498841)|SYSTEM_METHOD_EXIT|[20]|dom.Document.getRootElement() 03:30:42.343 (343531549)|SYSTEM_METHOD_ENTRY|[21]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343567322)|SYSTEM_METHOD_EXIT|[21]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343587891)|SYSTEM_METHOD_ENTRY|[22]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343610046)|SYSTEM_METHOD_EXIT|[22]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343628253)|SYSTEM_METHOD_ENTRY|[23]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343648610)|SYSTEM_METHOD_EXIT|[23]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343668516)|SYSTEM_METHOD_ENTRY|[24]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343688635)|SYSTEM_METHOD_EXIT|[24]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343706491)|SYSTEM_METHOD_ENTRY|[24]|dom.XmlNode.getText() 03:30:42.343 (343720855)|SYSTEM_METHOD_EXIT|[24]|dom.XmlNode.getText() 03:30:42.343 (343767676)|SYSTEM_METHOD_ENTRY|[24]|String.split(String) 03:30:42.343 (343862473)|SYSTEM_METHOD_EXIT|[24]|String.split(String) 03:30:42.343 (343897695)|SYSTEM_METHOD_ENTRY|[25]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343922033)|SYSTEM_METHOD_EXIT|[25]|dom.XmlNode.getChildElement(String, String) 03:30:42.343 (343935682)|SYSTEM_METHOD_ENTRY|[25]|dom.XmlNode.getText() 03:30:42.343 (343947779)|SYSTEM_METHOD_EXIT|[25]|dom.XmlNode.getText() 03:30:42.344 (344044998)|SYSTEM_METHOD_ENTRY|[27]|System.debug(ANY) 03:30:42.344 (344075607)|USER_DEBUG|[27]|DEBUG|@@@@@@00D28000000Heme!AQ8AQJQgA6fDVwxMdNpZPdg2ACWMoShT0GGXRWaI29XFqqVgjar0DHh_b3qg84gvGitO8U.P2mEy6.aoIcM4Z7qJEuecf0Ch 03:30:42.344 (344083721)|SYSTEM_METHOD_EXIT|[27]|System.debug(ANY) 03:30:42.344 (344139711)|SYSTEM_METHOD_ENTRY|[32]|System.HttpRequest.setEndpoint(String) 03:30:42.344 (344168650)|SYSTEM_METHOD_EXIT|[32]|System.HttpRequest.setEndpoint(String) 03:30:42.344 (344193175)|SYSTEM_METHOD_ENTRY|[33]|System.HttpRequest.setHeader(String, String) 03:30:42.344 (344224688)|SYSTEM_METHOD_EXIT|[33]|System.HttpRequest.setHeader(String, String) 03:30:42.344 (344245185)|SYSTEM_METHOD_ENTRY|[34]|Apex_Rest_DemoController.__sfdc_accName() 03:30:42.344 (344276949)|SYSTEM_METHOD_EXIT|[34]|Apex_Rest_DemoController.__sfdc_accName() 03:30:42.344 (344289182)|SYSTEM_METHOD_ENTRY|[34]|Apex_Rest_DemoController.__sfdc_accPhone() 03:30:42.344 (344298742)|SYSTEM_METHOD_EXIT|[34]|Apex_Rest_DemoController.__sfdc_accPhone() 03:30:42.344 (344308110)|SYSTEM_METHOD_ENTRY|[34]|Apex_Rest_DemoController.__sfdc_accWebsite() 03:30:42.344 (344316620)|SYSTEM_METHOD_EXIT|[34]|Apex_Rest_DemoController.__sfdc_accWebsite() 03:30:42.344 (344347885)|SYSTEM_METHOD_ENTRY|[34]|System.HttpRequest.setBody(String) 03:30:42.344 (344373477)|SYSTEM_METHOD_EXIT|[34]|System.HttpRequest.setBody(String) 03:30:42.344 (344395659)|SYSTEM_METHOD_ENTRY|[35]|System.HttpRequest.setMethod(String) 03:30:42.344 (344417222)|SYSTEM_METHOD_EXIT|[35]|System.HttpRequest.setMethod(String) 03:30:42.344 (344444026)|SYSTEM_METHOD_ENTRY|[36]|System.HttpRequest.setHeader(String, String) 03:30:42.344 (344470931)|SYSTEM_METHOD_EXIT|[36]|System.HttpRequest.setHeader(String, String) 03:30:42.344 (344497294)|SYSTEM_METHOD_ENTRY|[38]|System.Http.send(ANY) 03:30:42.346 (346921449)|CALLOUT_REQUEST|[38]|System.HttpRequest[Endpoint=https://ap2.salesforce.com/services/data/v34.0/sobjects/Account, Method=POST] 03:30:42.392 (392022552)|CALLOUT_RESPONSE|[38]|System.HttpResponse[Status=Unauthorized, StatusCode=401] 03:30:42.392 (392077223)|SYSTEM_METHOD_EXIT|[38]|System.Http.send(ANY)
this line:request.setHeader('Authorization', 'OAuth ' + SESSION_ID);
should be :req.setHeader('Authorization', 'OAuth ' + SESSION_ID);
(2) also try iusing: req.setHeader('Authorization', 'Bearer + SESSION_ID);
Best of Luck :-)
Tried the above, but no luck..Getting Invalid Session error
Regards
Can you please validate that your SOAP call to the other salesforce instance worked? (Lets call its SFDC-B)
You have used credentials of a SFDC-B' User while making the SOAP call to SFDC-B. If you login to SFDC-B and verify the user's login history to confirm the SOAP call actually made a call to SFDC-B and returned a SessionId?
Regards
Thanks for helping me out. I have resolved the issue. I made a OAuth call to target org using consumer, key, client secret, uid and password. Captured the sessionid and used that one making a rest call to rest resource.
Regards
I am also trying to do soemthing similar.Below is what I did. Getting Bad Request. Can you pls point out what is missing.
builder = new PostMethod("https://gus.salesforce.com/services/data/v20.0/sobjects/Attachment/");
builder.setRequestHeader("Authorization","OAuth " + lr.getSessionId());
httpclient.executeMethod(builder);
System.out.println(builder.getStatusText()); //Bad Request
Thanks and Regards,
-Esha Sharma
Can u please post ur entire code so tht i can have a better look into that.
Regards
Below is what I am doing:
byte[] data = IOUtils.toByteArray(new FileInputStream(f));
JSONObject content = new JSONObject();
if (attachment != null) {
content.put("Name", attachment);
}
content.put("Body", new String(Base64.encode(data)));
content.put("ParentId", caseid);
builder = new PostMethod("https://gus.salesforce.com/services/data/v20.0/sobjects/Attachment/");
builder.setRequestEntity(new StringRequestEntity(content.toString(), "application/json", null));
builder.setRequestHeader("Authorization","OAuth " + SessionId);
httpclient.executeMethod(builder);
This code works for me but for files for smaller size. I tried attaching file of 50+ MB and it threw bad request error for me. Can you please help. I need a solution for attaching files of larger size (around 1GB).
Regards,
-Esha
I have subscribed for developer account in Salesforce. Now I want to do some API calls to Salesforce. So as prerequisite I have created a connected app called Mule in sales force and I have enabled OAuth in it. API is enabled for my profile.
As mentioned in the link ( https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/quickstart_oauth.htm ) I am trying to get SessionID. I am using below link command.
curl https://login.salesforce.com/services/oauth2/token -d "grant_type=password" -d "client_id=******" -d "client_secret=*****" -d "username=mylogin@salesforce.com" -d "password=mypassword123456"
I got error {"error":"invalid_grant","error_description":"authentication failure"}
I tried same from postman using POST method, gave userid and password
https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=3MVG9YDQS5WtC11opKfz4w0XYTmO4dfE9Bwx4Ao7fy5fMPAuZfRBQFIIkUv78ln8gZ.bw3W2GicyQLnZyVu1I&client_secret=4284160506975427817
RESPONSE:
{
"error": "invalid_grant",
"error_description": "authentication failure"
}
can some one please help ?