本文参考官方文档和zero zhang的博客:

  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_integration_intro.htm

Salesforce调用外部接口的方法或者数据,常用的访问方式有两种:

  1. Soap方式:Web Service 通过XML方式调用Soap Web服务器;
  2. Rest方式:Http通过JSON使用REST方式调用服务器。

下面了解一下REST方式获取外部Service数据。

  • Salesforce 通过REST方式获取外部Service数据

      REST方式原理图如下:

  • Salesforce 通过REST方式访问外界站点步骤如下
    1. 将Webservice的授权端点地址添加到Remote Site中:set -> Administer->Security Site Settings->Remote Site Settings。
      Salesforce提供了两个测试URL。将两个测试的URL添加到Remote Site中。两个URL分别为:

    2. 代码进行访问,通过Http方式可以使用以下方法进行相关操作的访问:

  • 下面是我自己封装的一个简单的Salesforce调用外部接口的帮助类和测试类:
    1. Helper类:

      global class HttpHelper {
      
          private Http Http{get;set;}
      
          private HttpRequest Request{get;set;}
      
          private HttpResponse Response{get;set;}
      
          public HttpResponse service(String method,String url,String body,String contentType,String authoriziton,String certificateName){
      Http = new Http();
      Request = new HttpRequest();
      try{
      Request.setMethod(method);
      Request.setEndpoint(url);
      Request.setTimeout(120000);
      if(string.isEmpty(contentType) || string.isBlank(contentType)){
      Request.setHeader('Content-Type','application/json;charset=utf-8');
      }else{
      Request.setHeader('Content-Type',contentType);
      }
      if(string.isNotEmpty(authoriziton)&&string.isNotBlank(authoriziton)){
      Request.setHeader('Authorization', authoriziton);
      }
      if(string.isNotEmpty(certificateName)&&string.isNotBlank(certificateName)){
      Request.setClientCertificateName(certificateName);
      }
      if(string.isNotEmpty(body)&&string.isNotBlank(body)){
      Request.setBody(body);
      }
      Response = Http.send(Request);
      System.debug('Response:'+Response);
      }catch(Exception e){
      system.debug('RequstException:'+e);
      }
      return Response;
      } /**
      Execute the Get Method
      */
      public HttpResponse doGet(String url,String body,String authoriziton,String certificateName){
      return service('GET', url, body, null, authoriziton,certificateName);
      } /**
      * Execute the Post Method
      */
      public HttpResponse doPost(String url,String body,String authoriziton,String certificateName){
      return service('POST', url, body, null, authoriziton,certificateName);
      } }
    2. 需要注意的是在测试帮助类的时候,我们必须实现HttpCalloutMock的这个类并实现其方法respond(),如:
      @isTest global class HttpCallOutMockImpl implements HttpCalloutMock{
      global HttpResponse respond(HttpRequest request){
      //Optionally,only send a mock response for a specific endpoint.
      System.assertEquals('http://example.com/example/test',request.getEndpoint());
      System.assertEquals('GET',request.getMethod()); //Create a fake response
      HttpResponse response = new HttpResponse();
      response.setHeader('Content-Type', 'application/json');
      response.setBody('{"example":"test"}');
      response.setStatusCode(200);
      return response;
      }
      }
    3. 编写测试类,如:
      @isTest
      private class HttpHelperTest {
      @isTest static void testCallOut(){
      Test.setMock(HttpCalloutMock.class,new HttpCallOutMockImpl());
      HttpHelper httpHelper = new HttpHelper();
      HttpResponse resp= httpHelper.doGet('http://example.com/example/test', null, null, null);
      string contentType = resp.getHeader('Content-Type');
      System.assert(contentType == 'application/json');
      String actualValue = resp.getBody();
      System.debug('Body:'+actualValue);
      String expectedValue = '{"example":"test"}';
      System.assertEquals(actualValue, expectedValue);
      System.assertEquals(200, resp.getStatusCode());
      } }

      注:测试类必须加上标记@IsTest 

  

Salesforce Invoking Http Callouts and Testing Http Callouts的更多相关文章

  1. [PWA] Disable Text Selection and Touch Callouts in a PWA on iOS

    Because an installed PWA is really just a web app running in a browser, there are some browser behav ...

  2. salesforce 零基础学习(三十三)通过REST方式访问外部数据以及JAVA通过rest方式访问salesforce

    本篇参考Trail教程: https://developer.salesforce.com/trailhead/force_com_dev_intermediate/apex_integration_ ...

  3. salesforce 零基础开发入门学习(五)异步进程介绍与数据批处理Batchable

    本篇知识参考:https://developer.salesforce.com/trailhead/force_com_dev_intermediate/asynchronous_apex/async ...

  4. 【转载】salesforce 零基础开发入门学习(五)异步进程介绍与数据批处理Batchable

    salesforce 零基础开发入门学习(五)异步进程介绍与数据批处理Batchable   本篇知识参考:https://developer.salesforce.com/trailhead/for ...

  5. 学习Salesforce | Platform Developer Ⅰ 平台初级开发认证考试指南及备考资源

    一.平台开发人员考试计划 Salesforce平台开发人员初级认证面向具有在Lightning平台上构建自定义应用程序的知识.技能和经验的个人. 该认证考核Lightning平台的基本编程能力,并会使 ...

  6. Salesforce Integration 概览(三) Remote Process Invocation—Fire and Forget(远程进程调用-发后即弃)

    本篇参考:https://resources.docs.salesforce.com/sfdc/pdf/integration_patterns_and_practices.pdf 我们在上一篇讲了远 ...

  7. 四、Salesforce Styles_1

    1.静态变量的使用:<apex:stylesheet value="{!$Resource.TestStyles}"/>2.<apex:page><s ...

  8. Unit Testing a zend-mvc application

    Unit Testing a zend-mvc application A solid unit test suite is essential for ongoing development in ...

  9. [译]36 Days of Web Testing(二)

    Day 7: Http 和 Https Why? 当在网络上传输一些私人,敏感信息时,应该采用加密的手段来保证这些信息在传输的过程中不被侦测到.Https协议正是这种实现机制. Https是一种广泛使 ...

随机推荐

  1. Scrapy中间件user-agent和ip代理使用

    一.定义实现随机User-Agent的下载中间件 1.在middlewares.py中完善代码 import random from Tencent.settings import USER_AGEN ...

  2. Excel身份证验证,身份证校验公式

    =IF(LEN(Q4)=0,"空",IF(LEN(Q4)=15,"老号",IF(LEN(Q4)<>18,"位数不对",IF(CH ...

  3. 为什么Python是最适合初创公司的编程语言?

    为什么Python是最适合初创公司的编程语言? 选自Medium 作者:Gleb Pushkov 京东云开发者社区编译 对于初创公司而言,要在众多编程语言中为公司选择一个正确.合适的语言绝非易事. 如 ...

  4. CPU温度的实现

    CPU温度需要安装的模块:apt-get install lm-sensors   然后再安装:pip install sensors.py 代码如下: #coding=utf-8import sen ...

  5. linux 增加虚拟内存swap(使用文件)

    1.简介 如果你的服务器的总是报告内存不足,并且时常因为内存不足而引发服务被强制kill的话,在不增加物理内存的情况下,启用swap交换区作为虚拟内存是一个不错的选择. 为了测试一些功能我在阿里云购买 ...

  6. DAY2:数据类型Python3.6

    数字 1.int(整型) 2. long(长整型) 3.float(浮点型) 4.complex(复数)  布尔值 1.真或假 1或0表示 字符串 知识补充 字符串转二进制 mes = "北 ...

  7. python模块之json_pickle_shelve

    序列化:明显是json重要,并且应用场景多. #!/usr/bin/env python # coding:utf-8 import json ## 非常重要的模块,用于不同种编程语言间交换数据. d ...

  8. NIO 概述 与 通信实例

    NIO 简述: NIO是在jdk1.4之后加入的一种基于缓冲区(buffer)和通道(channel)的I/O方式, nio是同步非阻塞的i/o模式,同步是指线程不断地轮询i/o事件,非阻塞是在处理i ...

  9. nginx——优化 Nginx 连接超时时间

    1. 什么是连接超时 (1) 举个例子,某饭店请了服务员招待顾客,但是现在饭店不景气,因此要解雇掉一些服务员,这里的服务员就相当于 Nginx 服务建立的连接 (2) 当服务器建立的连接没有接收处理请 ...

  10. 2017-9-10"切题如切菜杯"模拟赛T4 ZZI

    题目 YYH拿到了父亲给的钱欣喜若狂,把这些钱拿来造了n栋房子.现在他要给这些房子通电.他有两种方法:第一种是在房间里搭核电发电机发电,对于不同的房子,他需要花不同的代价Vi:,第二种是将有电的房子i ...