REST API
REST
API
Server ORG:
1. Creata Connected app (Setup>>Create>>Apps>>Connected Apps:New) by providing the Callback URL and NOTE Consumer
key and Consumer Secret to forward to Client Org.
Callback URL for
SFDC is https://login.salesforce.com/services/oauth2/callback
2. Create the
Rest Resource
@RestResource(urlMapping='/MappingDataService/*')
global with sharing class
MappingData {
@HttpPost
global static void MappingDetails(String
Name,String Phone){
system.debug('---name---'+name);
system.debug('---Phone---'+Phone);
Account objA = new Account();
objA.Name = Name;
objA.Phone = Phone;
insert objA;
}
}
Client ORG:
Page:
<apex:page
controller="AccInsertClas">
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection
columns="1">
<apex:inputfield
value="{!objA.Name}"/>
<apex:inputfield
value="{!objA.Phone}"/>
</apex:pageBlockSection>
<apex:commandButton
value="Save" action="{!doSave}"
style="margin-left:20%;"/>
</apex:pageBlock>
</apex:form>
</apex:page>
Controller
class:
public with sharing class
AccInsertClas {
public void doSave() {
string username = 'test@gmail.com';
string password =
'test@123XlpZxtqhPwrY96BgoAsjaDlU';
string ConsumerKey =
'ddddd6d_Btp4xp4AGZRP.n5EoVhmYQjQH6IMxRk1LO.v8FcqJsNqriKPd4bp5dlfmnU6W.vFWTQ5dP7U1Ajf';
string clientId = '4g555117865294009';
string URI =
'https://ap1.salesforce.com/services/oauth2/token?grant_type=password&' +
'client_id=' + ConsumerKey + '&' + 'client_secret=' + clientId + '&'
+ 'username=' + username + '&' + 'password=' + password;
HttpRequest req = new
HttpRequest();
req.setEndpoint(URI);
req.setMethod('POST');
Http http = new Http();
HTTPResponse res =
http.send(req);
System.debug('*** After
Authentication...'+res.getBody());
string accsToken = '';
JSONParser parser1 = JSON.createParser(res.getBody());
while (parser1.nextToken() != null)
{
if ((parser1.getCurrentToken()
== JSONToken.FIELD_NAME) && (parser1.getText() == 'access_token')) {
parser1.nextToken();
accsToken = parser1.getText();
}
}
system.debug('accsToken===========>'+accsToken);
URI =
'https://ap1.salesforce.com/services/apexrest/MappingDataService/MappingData';
req =
new HttpRequest();
req.setEndpoint(URI);
req.setMethod('POST');
req.setHeader('content-type','application/json');
string postData = '{ \"Name\":
\"'+ objA.Name +'\",\"Phone\": \"'+ objA.Phone
+'\"}';
system.debug('--postData--->'+postData);
req.setBody(postData);
req.setHeader('Authorization', 'OAuth '
+ accsToken);
res = http.send(req);
system.debug('----res--->'+res);
}
public Account objA{get;set;}
public AccInsertClas(){ // Constructor
objA =new Account();
}
}
|
Comments
Post a Comment