Salesforce中通过SOAP API开发java的web service服务以及踩坑

1.下载Salesforce平台中WSDL文件

首先需要的是自己Salesforce平台的权限通过。登陆自己的Salesforce,下载WSDL文件。

依次点击右上角你的名字中设置--》集成--》API

在页面上选择要生成WSDL的类型,在弹出的页面选择 右键 -->页面另存为,即可,如下两图显示:

8d3cdd530124ad7e915096c1baacf31ab94.jpg

分别下点生成企业WSDL,生成合作伙伴WSDL,生成元数据WSDL

203d262dbd5dc0ada3436d330e6862d61df.jpg

点击鼠标右键将文件另保存,可为.xml的形式也可以为.wsdl的文件形式

770cffd580f2eba136274ebb8d6dad7dc7f.jpg

2.下载并构建WSC Jar,然后把对应的wsdl文件编译成对应jar

Wsc.jar 下载地址:https://mvnrepository.com/artifact/com.force.api/force-wsc 选择最新版本的

选择下图中的jar就能下载jar包到本地啦(对应jdk版本1.8或者以上)

75d9364ae196adc7291a61d5626ee7eefab.jpg

ST4-4.0.8.jar (https://www.stringtemplate.org/download.html)

如果没有会报错:

Exception in thread "main" java.lang.NoClassDefFoundError:org/stringtemplate/v4/STGroupDir

Antlr-runtime-3.5.2.jar (https://mvnrepository.com/artifact/org.antlr/antlr-runtime/3.5.2)

用于java代码运行时构造,编译,转换的框架。

没有的话报错:

Exception in thread "main" java.lang.NoClassDefFoundError: org/antlr/runtime/CharStream

Tools.jar (安装jdk的目录下有,无需下载。直接复制)

d414a94f1368e1642109af8e1a713539c84.jpg

把刚才下载的jar包和3个wsdl文件放在同一个文件夹中(以下enterprise.jar,metadata.jar,partner.jar是通过下面cmd命令生成jar的)

8177dbf882633f06f6d076a15fcee5e155e.jpg

打开cmd,将路径定位到刚才的文件目录。

      a45a1229efcf3e3062c48706f8c9aa58c25.jpg

输入 java -classpath antlr-runtime-3.5.2.jar;tools.jar;st4-4.0.4.jar;force-wsc-45.1.0.jar com.sforce.ws.tools.wsdlc wsdl.xml enterprise.jar

       0d3c2df07160e14db720397d74db125447d.jpg

     java -classpath antlr-runtime-3.5.2.jar;tools.jar;st4-4.0.4.jar;force-wsc-45.1.0.jar com.sforce.ws.tools.wsdlc wsdl.jsp.xml partner.jar

    f166291a9547534484cfed1865fba1d1401.jpg

   java -classpath antlr-runtime-3.5.2.jar;tools.jar;st4-4.0.4.jar;force-wsc-45.1.0.jar com.sforce.ws.tools.wsdlc metadata.xml metadata.jar

   ff003050667c558c63045d13289873b076e.jpg

3.创建程序并引用外部jar文件

   创建java程序和引用jar外部包我就不解释,要应用的jar就是上文生成的3个jar(enterprise.jar,metadata.jar,partner.jar),对,也要 force-wsc-45.1.0.jar 

打开Eclipse创建一个JAVA项目,将上面说的四个jar包引进项目。

贴上接口代码,本例用的salesforce自带的对象Accout

package com.yipan;


import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.SaveResult;
import com.sforce.soap.enterprise.sobject.Account;

import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class Test {
    static final String USERNAME = "YOUR-USERNAME";                   //Salesforce账号中的用户名
    static final String PASSWORD = "YOUR-PASSWORD&security token";    //密码,这个密码有点特殊,需要在密码后面加入安全标记
    static EnterpriseConnection connection;

      public static void main(String[] args) {

        ConnectorConfig config = new ConnectorConfig();
        config.setUsername(USERNAME);
        config.setPassword(PASSWORD);
            
        try {
          
          connection = Connector.newConnection(config);
          System.out.println("Auth EndPoint: "+config.getAuthEndpoint());
          System.out.println("Service EndPoint: "+config.getServiceEndpoint());
          System.out.println("Username: "+config.getUsername());
          System.out.println("SessionId: "+config.getSessionId());

          // 增删改查
            queryContacts();
            //createAccounts();
           //updateAccounts();
          //deleteAccounts();
          
          
        } catch (ConnectionException e1) {
            e1.printStackTrace();
        }  

      }
      
      // queries and displays the 5 newest contacts
      private static void queryContacts() {
        
        System.out.println("Querying for the 5 newest Account...");
        
        try {
           
          // query for the 5 newest contacts  
          //SELECT Id, FirstName, LastName, Account.Name " + "FROM Contact WHERE AccountId != NULL ORDER BY CreatedDate DESC LIMIT 5    
          QueryResult queryResults = connection.query("SELECT Id, Name,NumberOfEmployees FROM Account WHERE ID !=NULL ORDER BY CreatedDate DESC LIMIT 5");
          if (queryResults.getSize() > 0) {
            for (int i=0;i<queryResults.getRecords().length;i++) {
              // cast the SObject to a strongly-typed Contact
              //Contact c = (Contact)queryResults.getRecords()[i];
                Account c=(Account)queryResults.getRecords()[i];
              System.out.println("Id: " + c.getId() + " - Name: "+c.getName()+"NumberOfEmployees: "+c.getNumberOfEmployees());
            }
          }
          
        } catch (Exception e) {
          e.printStackTrace();
        }    
        
      }
      
      // create 5 test Accounts
      private static void createAccounts() {
        
        System.out.println("Creating 5 new test Accounts...");
        Account[] records = new Account[2];
        
        try {
           
          // create 5 test accounts
          for (int i=0;i<2;i++) {
            Account a = new Account();
            a.setName("hello"+i);
            records[i] = a;
          }
          
          // create the records in Salesforce.com
          SaveResult[] saveResults = connection.create(records);
          
          // check the returned results for any errors
          for (int i=0; i< saveResults.length; i++) {
            if (saveResults[i].isSuccess()) {
              System.out.println(i+". Successfully created record - Id: " + saveResults[i].getId());
            } else {
              com.sforce.soap.enterprise.Error[] errors = saveResults[i].getErrors();
              for (int j=0; j< errors.length; j++) {
                System.out.println("ERROR creating record: " + errors[j].getMessage());
              }
            }    
          }
          
        } catch (Exception e) {
          e.printStackTrace();
        }    
        
      }
      
      // updates the 5 newly created Accounts
      private static void updateAccounts() {
        
        System.out.println("Update the 5 new test Accounts...");
        Account[] records = new Account[5];
        
        try {
           
          QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
                  "CreatedDate DESC LIMIT 5");
          if (queryResults.getSize() > 0) {
            for (int i=0;i<queryResults.getRecords().length;i++) {
              // cast the SObject to a strongly-typed Account
              Account a = (Account)queryResults.getRecords()[i];
              System.out.println("Updating Id: " + a.getId() + " - Name: "+a.getName());
              // modify the name of the Account
              a.setName(a.getName()+" -- UPDATED");
              records[i] = a;
            }
          }
          
          // update the records in Salesforce.com
          SaveResult[] saveResults = connection.update(records);
          
          // check the returned results for any errors
          for (int i=0; i< saveResults.length; i++) {
            if (saveResults[i].isSuccess()) {
              System.out.println(i+". Successfully updated record - Id: " + saveResults[i].getId());
            } else {
            com.sforce.soap.enterprise.Error[] errors = saveResults[i].getErrors();
              for (int j=0; j< errors.length; j++) {
                System.out.println("ERROR updating record: " + errors[j].getMessage());
              }
            }    
          }
          
        } catch (Exception e) {
          e.printStackTrace();
        }    
        
      }
      
      // delete the 5 newly created Account
      private static void deleteAccounts() {
        
        System.out.println("Deleting the 5 new test Accounts...");
        String[] ids = new String[5];
        
        try {
           
          QueryResult queryResults = connection.query("SELECT Id, Name FROM Account ORDER BY " +
                  "CreatedDate DESC LIMIT 5");
          if (queryResults.getSize() > 0) {
            for (int i=0;i<queryResults.getRecords().length;i++) {
              // cast the SObject to a strongly-typed Account
              Account a = (Account)queryResults.getRecords()[i];
              // add the Account Id to the array to be deleted
              ids[i] = a.getId();
              System.out.println("Deleting Id: " + a.getId() + " - Name: "+a.getName());
            }
          }
          
          // delete the records in Salesforce.com by passing an array of Ids
          com.sforce.soap.enterprise.DeleteResult[] deleteResults = connection.delete(ids);
          
          // check the results for any errors
          for (int i=0; i< deleteResults.length; i++) {
            if (deleteResults[i].isSuccess()) {
              System.out.println(i+". Successfully deleted record - Id: " + deleteResults[i].getId());
            } else {
              com.sforce.soap.enterprise.Error[] errors = deleteResults[i].getErrors();
              for (int j=0; j< errors.length; j++) {
                System.out.println("ERROR deleting record: " + errors[j].getMessage());
              }
            }    
          }
          
        } catch (Exception e) {
          e.printStackTrace();
        }    
        
      }

}
运行项目(在此截图查询的记录,其它的都测试过了)

ad81ac2236b7c4f7a3446f32057655fa95e.jpg

根据控制台ID可以去salesforce查询到该客户

35ebe108b59c60f7a11e90ae5e7e8bb1744.jpg

如果需要用到新的对象,比如我自己创建的Position对象,那么可以在对象的详细页面找到对象对应的api名称,以及对象中字段api名称,如下图

image

image

找到对应的api名称后,如果需要创建一条Position纪录,那么可以这样new一个对象  Position__c a = new Position__c(); 然后通过Set的扩展方法来对对象字段的值进行赋值便可。

转载于:https://my.oschina.net/u/3459265/blog/3036021

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值