Analysis of get and post requests in salesforce rest integration mode (continued) —- get salesforce access_token

Get salesforce access_token

In the previous article, we have briefly introduced the rest interface of salesforce. If you have a better understanding of java servlet, it should be easy to understand.

Our article mainly introduces how to obtain the access_Token of salesforce through the java program, how to understand the access_token here, in layman’s terms, it is to exchange a token authentication through a series of established parameters, and only have the authority to call the interface according to this token .

What parameters do we need to get access_token:

  • The appid of the linker
  • Connector’s appsecret
  • userName
  • password
    Write the picture description here
    1. As shown in the picture above: we click Settings -> Create -> Apps -> Connected Apps once, if you use it for the first time, you can create one. like the one shown in the picture
    2. The two parameters userName and password are for us to prepare a license for interface use in the system, and this user can be set to log in using api.

Get access_token

package cn.lnc.course.util;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.net.ssl.SSLContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;




public class GetTokenUtil {
    public static Log log=LogFactory. getLog(GetTokenUtil. class);
    public static void main(String[] args) throws Exception {
        OperateProperties properties = new OperateProperties();
        Map<String,String> weChatMap = properties.getProperties("/SFDC.properties");
        System.out.println(getAccesToken(weChatMap.get("clientId"), weChatMap.get("clientSecret"), weChatMap.get("username"), weChatMap.get("password" )));
    }


    public static String getAccesToken(String clientId,String clientSecret,String userName,String password){
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            formparams.add(new BasicNameValuePair("grant_type","password"));
            formparams.add(new BasicNameValuePair("client_id",clientId));
            formparams.add(new BasicNameValuePair("client_secret",clientSecret));
            formparams.add(new BasicNameValuePair("username",userName));
            formparams.add(new BasicNameValuePair("password",password));


            UrlEncodedFormEntity uefEntity;
            try {
                 OperateProperties properties = new OperateProperties();
                 Map<String,String> oauthMap = properties.getProperties("/SFDCInterface.properties");
                 System.out.println("===Get Token===");
                 String oauthUrl = oauthMap. get("oauthAction");
                 uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                 Map<String, String> resMaps = post(oauthUrl, uefEntity, null);
                 String resString = resMaps. get("body");
                 Pattern pattern = Pattern.compile("\{\"access_token\":\"(.*?)\\ "");
                 Matcher matche = pattern. matcher(resString);
                 while(matche. find()) {

                     log.debug("===Get Token===");
                     System.out.println("===successful return===" + matche.group(1));
                     return matche. group(1);
                 }
                 return null;
            } catch (Exception e) {
                System.out.println("===Exception return===" + e.getMessage());
            }
            return null;
    }
    private static CloseableHttpClient buildSSLCloseableHttpClient() throws Exception {
         SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
      // trust all
      public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
          return true;
      }
        }).build();
         SSLConnectionSocketFactory factory=new SSLConnectionSocketFactory(sslContext, new String[]{<!-- -->"TLSv1","TLSv1.1"}, sslContext.getDefaultSSLParameters().getCipherSuites(),
         SSLConnectionSocketFactory. getDefaultHostnameVerifier());
         return HttpClients.custom().setSSLSocketFactory(factory).build();

    }

    public static Map<String, String> post(String url, HttpEntity uefEntity, Map<String, String> headerMaps) throws Exception{
        CloseableHttpClient httpclient = buildSSLCloseableHttpClient();
        HttpPost httppost = new HttpPost(url);
        if(headerMaps != null){
            for (String key : headerMaps. keySet()) {
                httppost.addHeader(key, headerMaps.get(key));
            }
        }
        httppost.setEntity(uefEntity);
        try {
            CloseableHttpResponse response = httpclient. execute(httppost);
            HttpEntity resEntity = response. getEntity();
            String body = (resEntity != null ? EntityUtils.toString(resEntity, "UTF-8") : "");
            System.out.println("---------body-----------" + body);
            Map<String, String> resMaps = new HashMap<String, String>();
            resMaps.put("status", response.getStatusLine().toString());
            resMaps. put("body", body);
            return resMaps;
        } catch (IOException e) {
            throw e;
        } finally {
            try {
                httpclient. close();
            } catch (IOException e) {
                System.out.println("caught exception");
            }
        }
    }
}


SFDC.properties

clientId=3MVG9YDQS5WtC1xxxxxxrsvzbZunFqfcxl3NR4mM5tieQ0vmPxHyCOlEKJFhmqj8FJuH.51dK7
clientSecret=5780xxxxxx44475
[email protected]
password=xxxxxx
token=00D0k0000000crc!ARMAQOvF4whWOxxxxxxxOyXBb0cBLQ_xxxxxxx8c_pLK0PFmpVGxVldUXuITo3cYKP1

Use the obtained access_token to call the interface

package cn.lnc.course.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class SFDCSendUtil {
    /**
    * Push data tools to SFDC
    *
    * @author ningchao.li
    * @date 2018-07-31
    * @param action This is used for maintenance in SFDCInterface.properties, the interface name is maintained through the configuration file
    */
    public static String sendReq(String action,String jsonStr) throws Exception {
        System.out.println("Send data 1");
        String result = "";
        //Obtain the token, instead of obtaining the token every time, use a scheduled task to automatically obtain it every two hours.
        //String token = getAccesToken();
        OperateProperties properties = new OperateProperties();
        Map<String,String> weChatMap = properties.getProperties("/SFDC.properties");
        String token = weChatMap. get("token");
// String s = "{"requestPara":{"Request_Id":"DJ001"}}";
        StringEntity emtity = new StringEntity(jsonStr,"utf-8");
        Map<String, String> map = new HashMap<String, String>();
        map.put("Authorization", "Bearer " + token);
        map.put("Content-Type", "application/json;charset=utf-8");
        System.out.println("Send data 2");
        try {
             // Read the interface address that needs to be called according to the configuration file
             Map<String,String> urlMap = properties.getProperties("/SFDCInterface.properties");
             // The interface address is specified in the configuration file, and the URL is obtained here
             String oauthUrl = urlMap. get(action);
             Map<String,String> resultMap = GetTokenUtil.post(oauthUrl,emtity,map);
             result = resultMap. get("body");
             System.out.println("Interface call result" + resultMap);


        } catch (Exception e) {
            System.out.println("Exception" + e);
        }

        return result;
        }
}

SFDCInterface.properties

CreateAccount=https://ap4.salesforce.com/services/apexrest/Rest_CreateAccount
oauthAction=https://liningchao-dev-ed.my.salesforce.com/services/oauth2/token
CreateWeChatUser=https\://ap4.salesforce.com/services/apexrest/Rest_CreateWeChatUser

In the above code, we have achieved the token of salesforce, and implemented the function of calling the SFDC interface according to the token. In fact, we can also put the code for obtaining the token before calling the interface, but make a timing program. Of course, if it is a web application, it can be placed directly in the listener. The purpose is to automatically refresh the token value in the configuration file every two hours, so as to ensure the full utilization value of the API. (The timeliness of the token is two hours.)