本文参考官方文档和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. Linux 下编程

    关于Linux 下的C语言编译命令和编程要点! https://www.cnblogs.com/wfwenchao/p/3985153.html?utm_source=tuicool&utm_ ...

  2. 1 实现添加功能 1.1 定义一个学员类(Student),在Student类中定义姓名、性别和年龄属性,定义有 参数的构造方法来初始化所以的成员属性 1.2 创建学员类对象来存放学员信息,并且为每一个学生对象添加的相应的编号。并将 学员类对象添加到Map<Integer,Student>集合中 1.3 添加完成后,显示所有已添加的学员姓名 1.4 限制年龄文本框只能输入正整数,否则的会采

    学生类 package com.lanxi.demo1_3; public class Student { private String name; private String sex; priva ...

  3. ES6常用方法总结

    1.声明变量用let,声明常量用const(定义唯一的值),都没有预解释,也不存在变量提升: 2.箭头函数:有如下两种写法 1).表达式(函数体只有一行代码) a).let fn = p => ...

  4. java 方法的重载

    方法的重载:一个类中允许出现一个以上的同名方法,必须保证同名方法的参数列表不同    好处:方便阅读,优化程序设计    重载规则:重载方法名相同,但每个重载方法都必须有一个独一无二的参数类型列表,方 ...

  5. php websocket

    php websocket项目开发,推荐使用:Workerman 本片内容使用Workerman实现了简单的及时聊天功能,具体代码如下: <?php // phpinfo(); header(' ...

  6. JAVA8集合之List

    目录: 一.ArrayList概述 二.ArrayList的实现 1)成员变量 2)构造方法 3)元素添加 4)元素删除 5)元素修改 6)集合容量调整 7)集合转数组 三.总结 一.ArrayLis ...

  7. 清华机试中手机键盘问题求解 java 和 c

    题目描述:按照手机键盘输入字母的方式,计算所花费的时间 如:a,b,c都在“1”键上,输入a只需要按一次,输入c需要连续按三次.如果连续两个字符不在同一个按键上,则可直接按,如:ad需要按两下,kz需 ...

  8. Delphi编程之爬取贴吧图片最终版

    接着前面两篇文章的内容,我们今天把这个贴吧爬取图片的程序完善,让它具有可以下载贴吧多页和帖子多页图片的能力. 主界面设计如下,包含3个labelededit,3个button,1个memo,1个str ...

  9. C# socket通讯 send方法记录

    由于本人是Java入门的开发,在C#开发中遇到的问题,在此记录一下: 1.client端的send方法不管发送出去没发送出去,总是显示发送出去. 查资料得知,send方法是将数据发送到缓存区,并不是直 ...

  10. React native 中使用Fetch请求数据

    一.代码 import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from ' ...