I am trying to generate the access token using OAUTH 2.0 . Here is the full code but repsonse.getBody() is not giving me the JSON string.
I have 2 instances of salesforce sandbox api, data flow is from salesforceA(source) to salesforceB(destination)
Both users are having system admin profile.
In salesforceA(source) I have created a connected app, so I get clientID and client secret, callback URL is: http://ap2.salesforce.com/apex/MyResponse where Myresponse is a visualforce page.
In salesforceB(destination), in remote site settings I have registered the URL "https://login.salesforce.com/services/oauth/token'
apex controller and visual force page is in salesforceB(destination)
public class restExample1
{
public String ClientSecret{get;set;}
public String ClientID{get;set;}
public String UserName{get;set;}
public String Password{get;set;}
public String Result{get;set;}
public String accessToken{get;set;}
public PageReference GetAccessToken()
{
HttpRequest request=new HttpRequest();
request.setEndPoint('https://login.salesforce.com/services/oauth/token');
request.setMethod('POST');
String reqbody = 'grant_type=password&client_id='+clientId+'&client_secret='+clientSecret+'&username='+username+'&password='+password;
request.setBody(reqbody);
Http p=new Http();
HttpResponse response=p.send(request);
result=response.getBody();
system.debug('@@@result = '+result);
return null;
}
}
Myresponse visualforce page
<apex:page controller="restExample1">
<apex:form >
<apex:pageBlock title="RestApiExample">
<apex:pageBlockSection title="OAuth2.0 username & Password"
collapsible="false">
<apex:pageBlockSectionItem >
<apex:outputLabel value="ClientID"/>
<apex:inputText value="{!ClientID}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="ClientSecret"/>
<apex:inputText value="{!ClientSecret}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="UserName"/>
<apex:inputText value="{!UserName}"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem >
<apex:outputLabel value="Password"/>
<apex:inputText value="{!Password}"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton value="Get Access Token"
action="{!GetAccessToken}"
reRender="token"/>
</apex:pageBlockButtons>
</apex:pageBlock>
<apex:pageBlock title="Access Token"
id="token">
{!accesstoken}
</apex:pageBlock>
</apex:form>
</apex:page>
setEndPoint('https://test.salesforce.com/services/oauth2/token');