在Salesforce中创建Web Service供外部系统调用

在Salesforce中可以创建Web Service供外部系统调用,并且可以以SOAP或者REST方式向外提供调用接口,接下来的内容将详细讲述一下用SOAP的方式创建Web Service并且用Asp.net的程序进行简单的调用。

 

1):在Salesforce中创建如下Class

【注:要想使其成为web service,那么class一定要定义成global的,具体的方法要用 webService static 修饰】

【代码中省略了GenerateAccountFromXmlInfo方法的具体实现,细节请看:http://www.cnblogs.com/mingmingruyuedlut/p/3497646.html 】

global class SFAccountWebService {
    
    webService static string UpsertAccount(String accountXmlInfo) {
        Account currentAcc = GenerateAccountFromXmlInfo(accountXmlInfo);
        try
        {
            Account acc = [Select Id From Account a Where AccountNumber =: currentAcc.AccountNumber];
            if(acc != null){
                currentAcc.Id = acc.Id;
            }
            upsert currentAcc;
            return 'true';
        }
        catch(exception ex){
            return 'false';    
        }
    }
    
    
    private static Account GenerateAccountFromXmlInfo(String accountXmlInfo){
        Account currentAcc = new Account();
        // Parse the xml info to generate the Account Object
        return currentAcc;
    }
    
}

 

2):在保存好上述的class之后,我们到setup --> build --> develop --> apex classes 中找到刚刚保存的class,我们会发现在对应的Action中有WSDL这个选项,此选项就是Salesforce默认所提供的将Web Service的class转化成WSDL文件。如下图所示

 

3):点击上图的WSDL按钮,会看到如下界面,这里显示的是生成的WSDL文件的详细信息,我们点击鼠标右键,将此文件保存到本地,这里姑且取名为SFAccountWebService.wsdl

 

4):我们可以简单的创建一个WebApplication的project,如下图所示,点击Reference后进行Add Web Reference

5):接上图,在URL的输入框中选择我们刚刚生成的WSDL文件,填写好右下角的Web Service Name,然后点击Add Reference按钮,这样我们就已经应用到了我们所刚刚生成的Web Service,是不是很简单呢~~

 

6):由于我们是通过外部系统去访问Salesforce内部的资源,那么不可逃避的首先便是认证,也就是说,我们必须首先通过Salesforce的认证,获取登陆用户的SessionId,然后此SessionId将作为此后每次访问Salesforce内部资源的认证标识,只有这样我们才能顺利调用到我们对外开放的Web Service。

如何在外部系统进行登陆认证获取对应的SessionId呢?这就涉及到了Salesforce默认提供的另外一个Web Service,如下图所示:

【setup --> build --> develop --> api --> partner wsdl --> generate partner wsdl】

 

7):将此WSDL文件以相同的方式保存到本地,这里姑且取名为 SFCommonService.wsdl

 

8):在对应Web Application的project中以相同的方式引用此文件

 

9):可以简单的看一下最终的引用状态,如下图所示

 

10):如何进行调用对应的Web Service呢? 请看如下代码

【login方法的两个参数是:用户名和密码。注:这里的密码是 用户密码 + 所对应的token】

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using TestSFWebServiceApplication.SFCommonWebService;
using TestSFWebServiceApplication.SFAccountWebService;

namespace TestSFWebServiceApplication
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Call login function to get the session id
            SforceService sfService = new SforceService();
            LoginResult result = sfService.login(@"******************", @"***********************");
            string currentSessionId = result.sessionId;
            
            //Call our web service function
            string accountXmlInfo = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><Accounts><Account><AccountName>WebServiceTest001</AccountName><AccountNumber>AAA000-009</AccountNumber></Account></Accounts>";
            SFAccountWebServiceService sfAccountService = new SFAccountWebServiceService();
            SFAccountWebService.SessionHeader sfAccountHeader = new SFAccountWebService.SessionHeader();
            sfAccountHeader.sessionId = currentSessionId;
            sfAccountService.SessionHeaderValue = sfAccountHeader;
            string upsertResult = sfAccountService.UpsertAccount(accountXmlInfo);
        }
    }
}

 

11):那么在Salesforce中如何引用外部系统所提供的Web Service呢?请看下图,将外部的WSDL文件生成Salesforce中所对应的Class

之后的具体调用这里就不详细列举了,请看如下链接:http://www.cnblogs.com/mingmingruyuedlut/p/3512262.html  

 

更多内容请看如下链接:

http://shivasoft.in/blog/salesforce/consume-salesforce-web-service-in-c-net-application/

http://shivasoft.in/blog/salesforce/create-a-custom-web-service-in-salesforce-and-consume-it-in-c-net-application/

 

12):当然了我们可以创建对应的Rest Service供外部系统调用

12.1):在Salesforce中创建对应的Class,代码如下所示

@RestResource(urlMapping='/SFEricSunTestRestService')
global class SFEricSunTestRestService {

    @HttpGet
    global static string GetTestRestInfo(){
        string testInfo = 'Hello Rest Service.';
        return testInfo;
    }
}

这里的标识为 @RestResource(urlMapping='/.....') 这样所形成的Rest Service Uri 格式为 https://cs5.salesforce.com/services/apexrest/SFEricSunTestRestService

Http 的 GET 和 DELETE 方法不支持传递参数

 

12.2):在外部系统调用上面的Rest Service(Get 方法),代码如下所示

        private void TestSFRestService()
        {
            SforceService sfService = new SforceService();
            LoginResult result = sfService.login(@"......", @"......");
            string currentSessionId = result.sessionId;

            string restServiceURI = @"https://cs5.salesforce.com/services/apexrest/SFEricSunTestRestService";

            WebRequest request = WebRequest.Create(restServiceURI);
            request.Method = "GET";
            //request.ContentType = "application/xml";
            request.Headers.Add("Authorization:Bearer " + currentSessionId);

            WebResponse response = request.GetResponse();

            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string msg = reader.ReadToEnd();
            }

        }

 

12.3):也可以进一步扩展,代码如下

@RestResource(urlMapping='/SFEricSunTestRestService/*')
global class SFEricSunTestRestService {
    
    @HttpDelete
    global static string doDelete() {
        RestRequest req = RestContext.request;
        String name = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        return 'Delete ' + name;
    }
  
    @HttpGet
    global static string doGet() {
        RestRequest req = RestContext.request;
        String name = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
        return 'Get ' + name;
    }
  
    @HttpPost
    global static String doPost(String name, String age) {
        return 'Post' + name + ' ' + age;
    }
    
}

 

12.4):在外部系统调用上面的Rest Service,代码如下所示

        private void TestSFRestService()
        {
            SforceService sfService = new SforceService();
            LoginResult result = sfService.login(@"....", @"....");
            string currentSessionId = result.sessionId;

            string restServiceURI = @"https://cs5.salesforce.com/services/apexrest/SFEricSunTestRestService/MyName";

            WebRequest request = WebRequest.Create(restServiceURI);
            request.Method = "GET";
            //request.ContentType = "application/xml";
            request.Headers.Add("Authorization:Bearer " + currentSessionId);

            WebResponse response = request.GetResponse();

            if (response != null)
            {
                StreamReader reader = new StreamReader(response.GetResponseStream());
                string msg = reader.ReadToEnd();
            }

        }

这是对GET方法的调用,我们将Name放在了Url的最后面传递给Service中,如果想调用Delete的方法,那么将request.Method = "GET";修改成为request.Method = "DELETE";

这里的Post方法有些特殊,需要传递name和age参数(实质是就是将实参加入到request的body中一起发到目的端去请求),调用代码如下所示

 

 

这里提供了SOUP UI的截图如下所示:

 

 

12.5):如果我们想在Salesforce内部去调用对应的Rest Service,那么可以用如下方式

https://developer.salesforce.com/forums/#!/feedtype=SINGLE_QUESTION_SEARCH_RESULT&id=906F000000099zbIAA 

 

更加详细的信息请看如下链接:

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#CSHID=apex_web_services_methods.htm|StartTopic=Content%2Fapex_web_services_methods.htm|SkinName=webhelp

https://developer.salesforce.com/page/Creating_REST_APIs_using_Apex_REST 

 

 

 

 

posted @ 2014-01-01 08:57  Eric Sun  阅读(6530)  评论(1编辑  收藏  举报