用Java程序访问Salesforce Rest API

参考文章:https://ashishkeshari.com/index.php/2018/09/22/calling-salesforce-rest-api-web-services-using-oauth-2-0-and-java/

Salesforce允许外部应用程序访问它的Rest API,这样可以和Salesforce的数据进行交互。

这篇文章是介绍如何用Java程序,去访问Salesforce Rest API。我参考了上面的文章,但做的过程中还是遇到了一些问题,在这里记录下来。

1、首先完成Trailhead上的这篇Apex Web Services练习。保证你的Org里有CaseManager类里提供的Rest服务。

2、然后需要建一个Connected App,来接受你得请求并且发送access Token。(Salesforce有很多种认证流程,本文选的是username和password的流程)。建立过程简单记录一下:

保存之后,就会得到你自己的Consumer Key和Consumer Secret,如下图:

3、修正Java代码,把上面的两个值添加在java代码里:

  private static final String CLIENTID = "yourConsumerKey";
  private static final String CLIENTSECRET = "yourConsumerSecret";

然后在java代码里把username和password(密码后面要加上Security Token)填上自己的。

private static final String USERID = “yourSalesforceloginId”;
private static final String PASSWORD = “yourpasswordandSecurityTokenCombined”;

这样代码基本就准备好了。注意:这个java代码需要两个jar库,JSONHTTPClient,请下载。

我对参考文章中的代码进行了一些修改,先调用POST插入一条Case,然后再用GET这条Case的信息。代码如下:

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import java.io.IOException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONTokener;
import org.json.JSONException;

public class RestAPIClient {

  private static final String LOGINURL = "https://login.salesforce.com";
  private static final String GRANTTYPE = "/services/oauth2/token?grant_type=password";
  private static final String CLIENTID = "yourConsumerKey";
  private static final String CLIENTSECRET = "yourConsumerSecret";
  private static final String USERID = "yourSalesforceloginId";
  private static final String PASSWORD = "yourpasswordandSecurityTokenCombined";
  private static final String ACCESSTOKEN = "access_token";
  private static final String INSTANCEURL = "instance_url";

  private static String instanceUrl;
  private static Header oAuthHeader;
  private static Header printHeader = new BasicHeader("X-PrettyPrint", "1");
  private static String caseId;
  private static String caseNumber;
  private static String caseSubject;
  private static String caseStatus;
  private static String caseOrigin;
  private static String casePriority;

  public static void main(String[] args) {

    HttpClient httpclient = HttpClientBuilder.create().build();

    String loginURL = LOGINURL + GRANTTYPE + "&client_id=" + CLIENTID + "&client_secret=" + CLIENTSECRET + "&username="
        + USERID + "&password=" + PASSWORD;

    HttpPost httpPost = new HttpPost(loginURL);
    HttpResponse httpResponse = null;

    try {
      httpResponse = httpclient.execute(httpPost);
    } catch (ClientProtocolException clientProtocolException) {
      clientProtocolException.printStackTrace();
    } catch (IOException ioException) {
      ioException.printStackTrace();
    } catch (Exception exception) {
      exception.printStackTrace();
    }

    final int statusCode = httpResponse.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
      System.out.println("Error authenticating to Salesforce.com platform: " + statusCode);
      return;
    }

    String httpMessage = null;
    try {
      httpMessage = EntityUtils.toString(httpResponse.getEntity());
    } catch (IOException ioException) {
      ioException.printStackTrace();
    }

    JSONObject jsonObject = null;
    String accessToken = null;
    try {
      jsonObject = (JSONObject) new JSONTokener(httpMessage).nextValue();
      accessToken = jsonObject.getString(ACCESSTOKEN);
      instanceUrl = jsonObject.getString(INSTANCEURL);
      System.out.println("accessToken:" + accessToken);
      System.out.println("instanceUrl:" + instanceUrl);
    } catch (JSONException jsonException) {
      jsonException.printStackTrace();
    }

    oAuthHeader = new BasicHeader("Authorization", "OAuth " + accessToken);

    //getCases();
    createCase();
  	getCaseById(caseId);

    httpPost.releaseConnection();
  }

  public static void getCases() {

    System.out.println("****************Case QUERY**************");

    try {

      HttpClient httpClient = HttpClientBuilder.create().build();

      String finalURI = instanceUrl
          + "/services/data/v38.0/query?q=Select+Id+,+CaseNumber+,+Subject+,+Status+,+Origin+,+Priority+From+Case+Limit+10";
      System.out.println("Query URL: " + finalURI);
      HttpGet httpGet = new HttpGet(finalURI);
      httpGet.addHeader(oAuthHeader);
      httpGet.addHeader(printHeader);

      HttpResponse httpResponse = httpClient.execute(httpGet);

      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        String responseString = EntityUtils.toString(httpResponse.getEntity());
        try {
          JSONObject jsonObject = new JSONObject(responseString);
          System.out.println("JSON result of Query:\n" + jsonObject.toString(1));
          JSONArray jsonArray = jsonObject.getJSONArray("records");
          for (int i = 0; i < jsonArray.length(); i++) {
            caseId = jsonObject.getJSONArray("records").getJSONObject(i).getString("Id");
            caseNumber = jsonObject.getJSONArray("records").getJSONObject(i).getString("CaseNumber");
            caseSubject = jsonObject.getJSONArray("records").getJSONObject(i).getString("Subject");
            caseStatus = jsonObject.getJSONArray("records").getJSONObject(i).getString("Status");
            //caseOrigin = jsonObject.getJSONArray("records").getJSONObject(i).getString("Origin");
            casePriority = jsonObject.getJSONArray("records").getJSONObject(i).getString("Priority");
            // Since the values are available, can be used later to create objects.
            System.out.println("getJSONObject(i) = " + jsonObject.getJSONArray("records").getJSONObject(i));
          }
        } catch (JSONException jsonException) {
          jsonException.printStackTrace();
        }
      } else {
        System.out.print("Query was unsuccessful. Status code returned is " + statusCode);
        System.out.println(httpResponse.getEntity().getContent());
        System.exit(-1);
      }
    } catch (IOException ioException) {
      ioException.printStackTrace();
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }

  public static String createCase() {
    System.out.println("****************Case Creation**************");

    String finalURI = instanceUrl + "/services/apexrest/Cases/";
    try {

      JSONObject newCase = new JSONObject();
      newCase.put("subject", "Smallfoot Sighting!");
      newCase.put("status", "New");
      newCase.put("origin", "Phone");
      newCase.put("priority", "Low");

      System.out.println("JSON for case record to be inserted:\n" + newCase.toString(1));

      HttpClient httpClient = HttpClientBuilder.create().build();

      HttpPost httpPost = new HttpPost(finalURI);
      httpPost.addHeader(oAuthHeader);
      httpPost.addHeader(printHeader);
      StringEntity entityBody = new StringEntity(newCase.toString(1));
      entityBody.setContentType("application/json");
      httpPost.setEntity(entityBody);

      HttpResponse httpResponse = httpClient.execute(httpPost);

      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        String responseString = EntityUtils.toString(httpResponse.getEntity());
        caseId = responseString;
        System.out.println("New Case Id from response: " + caseId);
      } else {
        System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
      }
    } catch (JSONException jsonException) {
      System.out.println("Issue creating JSON or processing results");
      jsonException.printStackTrace();
    } catch (IOException ioException) {
      ioException.printStackTrace();
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  	return caseId;
  }
	
  public static void getCaseById(String cId) {

    System.out.println("****************Case QUERY**************");

    try {

      HttpClient httpClient = HttpClientBuilder.create().build();

      String finalURI = instanceUrl
    	+ "/services/apexrest/Cases/" + cId.substring(1,19);
      System.out.println("Query URL: " + finalURI);
      HttpGet httpGet = new HttpGet(finalURI);
      httpGet.addHeader(oAuthHeader);
      httpGet.addHeader(printHeader);

      HttpResponse httpResponse = httpClient.execute(httpGet);

      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        String responseString = EntityUtils.toString(httpResponse.getEntity());
        try {
          JSONObject jsonObject = new JSONObject(responseString);
          System.out.println("JSON result of Query:\n" + jsonObject.toString(1));
        	
        } catch (JSONException jsonException) {
          jsonException.printStackTrace();
        }
      } else {
        System.out.print("Query was unsuccessful. Status code returned is " + statusCode);
        System.out.println(httpResponse.getEntity().getContent());
        System.exit(-1);
      }
    } catch (IOException ioException) {
      ioException.printStackTrace();
    } catch (Exception exception) {
      exception.printStackTrace();
    }
  }

}

4、编译执行结果:

5、遇到的问题

     a.编译时,找不到http.ClientHead等,这个需要在classpath里指定你下载的那两个库的路径。

     b.运行时,“Error authenticating to Salesforce.com platform: 400”错误,请检查CLIENTID,CLIENTSECRET,USERID,PASSWORD的值,肯定哪个没设定正确。

发布了90 篇原创文章 · 获赞 3 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/sunnyboychina/article/details/102918967