用Springboot(java程序)访问Salesforce RestAPI

本文讲一下,如何从0构建一个Springboot的应用程序,并且和Salesforce系统集成,取得Salesforce里面的数据。

一、先在Salesforce上构建一个ConnectApp。

有了这个,SF才允许你和它集成。手顺如下:
在这里插入图片描述
在这里插入图片描述
保存后,会提示你10分钟后才能生效,先不用管它。
在这里插入图片描述

在这里插入图片描述
点击上面的“Manage Consumer Details”按钮,会生成你自己的Consumer Key和Secret,这个拷贝出来,之后Java代码里要用到。
在这里插入图片描述

二、构建Springboot工程

关于Java,Eclipse,Maven等的环境构建,就省略了。
先Download一个Springboot的工程:https://start.spring.io/
注意右边的Dependencies,一定要ADD上Spring Web
在这里插入图片描述
你会得到“Demo.zip”的工程,把它导入到Eclipse里面。

然后根据下面的引导:
https://spring.io/quickstart
确保你的Springboot工程可以正常运行。
在这里插入图片描述
下面直接上代码:
我在com.example.demo目录下,建立了如下的代码文件:
在这里插入图片描述

package com.example.demo;import java.util.HashMap;
import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;@RestController
public class TestController {@Autowiredprivate AccountService accountService;@GetMapping(value = "/accounts")public Map getAccounts() {try {return accountService.getAccountList();} catch (Exception e) {System.out.println(e.getMessage());}return new HashMap<String, String>();}
}
package com.example.demo;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;@RestController
public class AccountService {@Autowiredprivate SalesforceDataService salesforceDataService;public Map getAccountList() {String query = "SELECT Id, Name FROM Account";return salesforceDataService.getSalesforceData(query);}
}

SalesforceDataService这个类你可以理解为Dao,就是去SF里面取数据。
这里面的instanceUrlaccessToken是最下面的类(SalesforceAuthenticator)取得的。
有了这2个,才能去有权访问你的SF系统。
取数据的过程,是利用了SF的标准RESTAPI接口,instanceUrl + "/services/data/v52.0/query/?q=SELECT Id, Name FROM Account"
这里就不详细讲SF的接口内容了。

package com.example.demo;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;@Service
public class SalesforceDataService {public Map getSalesforceData(String query) {SalesforceAuthenticator salesforceAuthenticator = SalesforceAuthenticator.getSalesforceToken();try {RestTemplate restTemplate = new RestTemplate();String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8.toString());final String baseUrl = salesforceAuthenticator.instanceUrl + "/services/data/v52.0/query/?q="+ encodedQuery;URI uri = new URI(baseUrl);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);headers.add(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", salesforceAuthenticator.accessToken));HttpEntity<?> request = new HttpEntity<Object>(headers);ResponseEntity<Map> response = null;try {response = restTemplate.exchange(uri, HttpMethod.GET, request, Map.class);} catch (HttpClientErrorException e) {System.out.println(e.getMessage());}return response.getBody();} catch (Exception e) {System.out.println(e.getMessage());}return Collections.emptyMap();}
}

SalesforceAuthenticator这个类是为了取得:

  1. accessToken:访问令牌(即认证的通行证)
  2. instanceUrl:你真实的SF系统的URL

上面两个是如何取得的,稍微解释一下:
通过向SF发送HttpRequest(POST),
请求的目标URL为:https://login.salesforce.com/services/oauth2/token
通过用户名密码的方式进行,这里要注意的是Password要加上你的Security Token
client_idclient_secret设定为在SF里面取得的那两个很长的字符串。

package com.example.demo;import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;public class SalesforceAuthenticator {private static SalesforceAuthenticator salesforceAuthenticator = null; public static String accessToken;public static String instanceUrl;// you can replace "https://login.salesforce.com" with your own URLprivate static final String LOGINURL = "https://login.salesforce.com/services/oauth2/token";// Consumer Keyprivate static final String CLIENTID = "<Your-consumer-id>";// Consumer Secretprivate static final String CLIENTSECRET = "<Your-consumer-secret>";// Salesforce Login Usernameprivate static final String USERNAME = "<Your-username>";// Salesforce Login password+Security Tokenprivate static final String PASSWORD = "<Your-password+Security Token>";private SalesforceAuthenticator() {try {final String baseUrl = LOGINURL;URI uri = new URI(baseUrl);HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();params.add("username", USERNAME);params.add("password", PASSWORD);params.add("client_secret", CLIENTSECRET);params.add("client_id", CLIENTID);params.add("grant_type","password");HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(params, headers);RestTemplate restTemplate = new RestTemplate();ResponseEntity<Map> response = restTemplate.postForEntity(uri, request, Map.class);System.out.println("StatusCode = " + response.getStatusCode()); Map<String, String> responseBody = response.getBody();accessToken = responseBody.get("access_token");instanceUrl = responseBody.get("instance_url");System.out.println("accessToken = " + accessToken); System.out.println("instanceUrl = " + instanceUrl); }catch(Exception e) {System.out.println(e.getMessage()); 		}}public static SalesforceAuthenticator getSalesforceToken() { try {if (salesforceAuthenticator == null) { salesforceAuthenticator = new SalesforceAuthenticator();return salesforceAuthenticator;}else {return salesforceAuthenticator;}}catch(Exception e) {e.printStackTrace();System.out.println(e.getMessage());}return null;}
}

其他的文件都不用改什么。

然后启动,
在这里插入图片描述
然后浏览器输入:http://localhost:8080/accounts,你的SF中Account一览就出来了。
在这里插入图片描述

参考文章:
https://www.coditation.com/blog/salesforce-integration-with-spring-boot-application
https://dzone.com/articles/leveraging-salesforce-without-using-salesforce
Gitlab salesforce-integration-service

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/767558.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

云计算系统管理(ADMIN)

01. 公司需要将/opt/bjcat3目录下的所有文档打包备份&#xff0c;如何实现&#xff1f; 答案&#xff1a; # tar -czf /tmp/bjcat3.tar.gz /opt/bjcat302. 简述创建crontab计划任务的流程 答案&#xff1a; 利用crontab –e -u 用户名 进入计划任务编辑模式 分 时 日 月 周 …

揭秘.dataru勒索病毒,远离数据被锁的威胁

导言&#xff1a; 在网络安全领域&#xff0c;勒索病毒已成为一个日益严重的威胁。其中&#xff0c;.dataru勒索病毒以其独特的加密技术和狡猾的传播方式&#xff0c;让许多企业和个人遭受了巨大的损失。本文将深入剖析.dataru勒索病毒的特点、传播方式&#xff0c;并提出有效…

Android kotlin全局悬浮窗全屏功能和锁屏页面全屏悬浮窗功能二

1.前言 在进行app应用开发中,在实现某些功能中要求实现悬浮窗功能,分为应用内悬浮窗 ,全局悬浮窗和 锁屏页面悬浮窗功能 等,接下来就来实现这些悬浮窗全屏功能,首选看下第二部分功能实现 2.kotlin实现锁屏页面悬浮窗全屏功能二分析 悬浮窗是属于Android系统的一种浮动窗…

dddssss

import cv2 from cvzone.PoseModule import PoseDetectorif __name__ __main__:# cap cv2.VideoCapture(2.mp4)cap cv2.VideoCapture(0)detector PoseDetector()posList []while True:success, img cap.read()img detector.findPose(img)# 获取33个点的每一帧放到lmList…

web渗透测试漏洞流程:目标域名CDN绕过

1.2.1 判断域名是否存在CDN 首先,要验证一个域名是否正在使用CDN服务,我们可以借助在线工具如ChinaZ的Ping服务(http://ping.chinaz.com/)来进行测试。当通过该工具查询到的IP地址不止一个时,这通常意味着显示的IP列表并非直接指向实际服务器的唯一真实IP。比如,若结果显…

jenkins配置源码管理的git地址时,怎么使用不了 credential凭证信息

前提 Jenkins使用docker部署 问题 &#xff08;在jenlins中设置凭证的方式&#xff09;在Jenkins的任务重配置Git地址&#xff0c;并且设置了git凭证,但是验证不通过&#xff0c;报错; 无法连接仓库&#xff1a;Command "git ls-remote -h -- http://192.1XX.0.98:X02/…

Compose UI 之 Checkbox 复选框 RadioButton 单选框

Checkbox 复选框 & RadioButton 单选框 Checkbox 复选框提供了在多个选项中选择一个或多个选项的作用。 RadioButton 单选框提供了在多个选项中只能选择一个选项的作用。 下面就分别来介绍下 Android Compose UI 库中的 Checkbox 复选框 和 RadioButton 单选框。 Radio…

C语言中的运算符优先级详解与使用示例

以下是C语言中运算符优先级的&#xff0c;以及对每个运算符的详细解释&#xff1a; 优先级运算符类别运算符描述1后缀() 函数调用 ( 数组下标 )函数调用、数组元素访问. 结构体成员访问 -> 结构体指针成员访问访问结构体的成员 后缀自增 -- 后缀自减自增或自减操作&#xf…

模拟实现字符串库函数(一)

在C语言的标准库中提供了很多针对字符串的库函数&#xff0c;这篇文章我们会学习并模拟实现几个简单的库函数 求字符串长度函数strlen strlen函数我们在之前已经用过很多次了&#xff0c;同时也模拟实现过&#xff0c;但是都不是模仿标准库中的strlen来实现&#xff0c;首先我…

IOS苹果开发者账号封号的规避心得,利用好防关联工具避免APP下架问题

大家好我是咕噜美乐蒂&#xff0c;很高兴又和大家见面了&#xff01; 当涉及到避免 iOS 苹果开发者账号封号以及利用防关联工具来规避应用下架问题时&#xff0c;有一些具体的操作和注意事项可以帮助你更好地管理你的开发者账号和应用。 避免账号封号的规避心得&#xff1a; …

编程界的万能钥匙:揭秘程序员常用的超实用算法!

程序员常用的算法 引言一、排序算法&#xff1a;为数据秩序井然二、搜索算法&#xff1a;高效定位数据三、图算法&#xff1a;理解复杂网络结构四、动态规划&#xff1a;优化递归求解过程五、贪心算法&#xff1a;简单高效的局部最优解六、数据结构相关算法&#xff1a;必不可少…

2024-03-24 思考-MBTI-简要记录

摘要: 2024-03-24 思考-MBTI-简要记录 MBTI16型人格: MBTI16型人格在人格研究和评价中得到了广泛的应用。MBTI是一种基于瑞士心理学家荣格在理论基础上发展起来的人格分类工具。为了准确判断个人的心态偏好&#xff0c;将每个人分为16种不同的人格类型。这种分类方法不仅为我们…

Red and Black (DFS BFS)

//新生训练 #include <iostream> #include <algorithm> #include <bits/stdc.h> using namespace std; int a, b, sum; char c[20][20]; void dfs(int x, int y) {c[x][y] #;if (x - 1 > 0 && c[x - 1][y] .){sum;dfs(x - 1, y);}if (x 1 <…

vue2 脚手架

安装 文档&#xff1a;https://cli.vuejs.org/zh/ 第一步&#xff1a;全局安装&#xff08;仅第一次执行&#xff09; npm install -g vue/cli 或 yarn global add vue/cli 备注&#xff1a;如果出现下载缓慢&#xff1a;请配置npm 淘宝镜像&#xff1a; npm config set regis…

使用 STL 容器发生异常的常见原因分析与总结

目录 1、概述 2、使用STL列表中的元素越界 3、遍历STL列表删除元素时对迭代器自加处理有问题引发越界 4、更隐蔽的遍历STL列表删除元素时引发越界的场景 5、多线程同时操作STL列表时没有加锁导致冲突 6、对包含STL列表对象的结构体进行memset操作导致STL列表对象内存出异…

python之(19)CPU性能分析常见工具

Python之(19)CPU性能分析常见工具 Author: Once Day Date: 2024年3月24日 一位热衷于Linux学习和开发的菜鸟&#xff0c;试图谱写一场冒险之旅&#xff0c;也许终点只是一场白日梦… 漫漫长路&#xff0c;有人对你微笑过嘛… 全系列文章可参考专栏:Python开发_Once-Day的博客…

深度学习 tablent表格识别实践记录

下载代码&#xff1a;https://github.com/asagar60/TableNet-pytorch 下载模型&#xff1a;https://drive.usercontent.google.com/download?id13eDDMHbxHaeBbkIsQ7RSgyaf6DSx9io1&exportdownload&confirmt&uuid1bf2e85f-5a4f-4ce8-976c-395d865a3c37 原理&#…

查看文件内容的指令:cat,tac,nl,more,less,head,tail,写入文件:echo

目录 cat 介绍 输入重定向 选项 -b -n -s tac 介绍 输入重定向 nl 介绍 示例 more 介绍 选项 less 介绍 搜索文本 选项 head 介绍 示例 选项 -n tail 介绍 示例 选项 echo 介绍 输出重定向 追加重定向 cat 介绍 将标准输入(键盘输入)的内容打…

pta L1-077 大笨钟的心情

L1-077 大笨钟的心情 分数 15 退出全屏 作者 陈越 单位 浙江大学 有网友问&#xff1a;未来还会有更多大笨钟题吗&#xff1f;笨钟回复说&#xff1a;看心情…… 本题就请你替大笨钟写一个程序&#xff0c;根据心情自动输出回答。 输入格式&#xff1a; 输入在一行中给出…

ns3使用cppyy load_library报错

报错&#xff1a; File "/bake/source/ns-3.37/build/bindings/python/ns/__init__.py", line 353, in load_modulescppyy.load_library(library)File "/usr/local/lib/python3.8/dist-packages/cppyy/__init__.py", line 235, in load_librarysc gSystem…