How to Fetch Access Token in Salesforce


Gagan Bansal

Scenario: Access Token required to authorize the web service connection.

Components Required: One Apex Class (AuthorizationClass).

Points to Remember:

1.  Content Type differ as per source server. Here example relates to “application/json”.

2.  Other Possible values for ContentType can be: “application/xml” , “text/html”,etc

3.  JSON static Method “deserialize” is used to deserialize the specified JSON string into an Apex object of the specified type.

4. JSON static Method “createGenerator” is used which returns a new JSON generator

Solution:

public class AuthorizationClass{
public static string getAccessToken(){
//AccessToken received after setting up connection with server.
String AccessToken = ”;
try {
HttpRequest req = new HttpRequest();
//Here value is ‘POST’
req.setMethod(system.label.PostMethod);
//Setting Content Type as JSON format.
req.setHeader(‘Content-Type’, ‘application/json’);
//Endpoint for which Client ID and Client Search shared by source server to set up connection.
req.setEndpoint(system.label.AccessTokenEndpoint);
//JSON Generator to build JSON request.
Jsongenerator gen = JSON.createGenerator(true);
gen.writeStartObject();
//Client ID shared by source…

View original post 132 more words