73、salesforce通过JAVA来Call在salesforce中已经写好的Restful处理接口
/**
*使用salesforce通过REST方式作为webservice,需要以下几点
*1、类和方法需要global,方法需要静态
*2、类需要通过RestResource(UrlMapping='/page/*')注解声明
*3、@HttpGet和@HttpDelete不能有形参,可以通过URL?param或者URL/param方式传过来参数
**/
@RestResource(UrlMapping='/Merchandise/*')
global class MerchandiseRESTController {
global static final Integer PAGE_SIZE = 20;
public static string merchandiseName {get;set;}
public static string merchandiseId {get;set;} @HttpGet
global static List<Merchandise__c> getMerchandiseByName(){
RestRequest request = RestContext.request;
//grab the merchandise Id from the end of the URL
String currentPage = request.params.get('currentPage')!=null?request.params.get('currentPage'):'0';
Integer offsetNumber = Integer.valueOf(currentPage) * PAGE_SIZE;
merchandiseName = request.params.get('name');
String fetchSql;
if(merchandiseName!=null){
fetchSql = 'SELECT Quantity__c,Price__c,Name from Merchandise__c where Name=:merchandiseName';
}else{
fetchSql = 'SELECT Quantity__c,Price__c,Name from Merchandise__c limit:PAGE_SIZE offset:offsetNumber ';
}
List<Merchandise__c> merchandiseList = Database.query(fetchSql);
return merchandiseList;
} @HttpPost
global static Id insertMerchandise(String name,String price,String quantity){
System.debug('----------merchandise name---------'+name);
Merchandise__c merchandise = new Merchandise__c();
if(price!=null && price.isNumeric()){
merchandise.Price__c = Decimal.valueOf(price);
}
if(quantity!=null && quantity.isNumeric()){
merchandise.Quantity__c =Decimal.valueOf(quantity);
}
merchandise.Name = name;
insert merchandise;
return merchandise.Id;
} @HttpDelete
global static void deleteMerchandise(){
RestRequest request = RestContext.request;
merchandiseName = request.requestURI.substring(request.requestURI.lastIndexOf('/')+1);
String querySql = 'select Id from Merchandise__c where Name =:merchandiseName';
List<Merchandise__c> merchandiseList = Database.query(querySql);
if(merchandiseList!=null){
delete merchandiseList;
}
} @HttpPut
global static Id upsertMerchandise(String name,String price,String quantity){
Merchandise__c merchandise = new Merchandise__c();
merchandise.Name = name;
if(price!=null && price.isNumeric()){
merchandise.Price__c = Decimal.valueOf(price);
}
if(quantity!=null && quantity.isNumeric()){
merchandise.Quantity__c =Decimal.valueOf(quantity);
}
upsert merchandise;
return merchandise.Id; } /**@HttpPatch
global static Id updateMerchandise(){
RestRequest request = RestContext.request;
merchandiseName = request.requestURI.substring(
request.requestURI.lastIndexOf('/')+1);
String querySql = 'select Id from Merchandise__c where Name =:merchandiseName';
List<Merchandise__c> merchandiseList = Database.query(querySql);
// Deserialize the JSON string into name-value pairs
Map<String, Object> params = (Map<String, Object>)JSON.deserializeUntyped(request.requestbody.tostring());
// Iterate through each parameter field and value }**/ }
上边是salesforce中的接口实现,通过restful方式来处理http请求
下边则是JAVA中调用上边salesforce中已经处理好的restful的http接口
package com.test.salesforce.restful; import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.DefaultedHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener; public class TestSalesforceRestful {
static final String USERNAME = "weizhen.zhao@pactera.com";
static final String PASSWORD = "zwz87865918vYoQKmkHZ3CHvlWxktmXybWi";
static final String LOGINURL = "https://login.salesforce.com";
static final String GRANTSERVIVE = "/services/oauth2/token?grant_type=password";
static final String CLIENTID = "3MVG9YDQS5WtC11rl9X0l.9UJjmHTftDEUlhQz8SsxqKUk5iRxSgSp2aeKxM1NHJBkzp.VJqIT56XXPnLk5oi";
static final String CLIENTSECRET = "9102086465628528777";
private static String REST_ENDPOINT = "/services/apexrest";
private static String baseUri;
private static Header oauthHeader;
private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1"); public static void main(String[] args) {
// 测试restful 创建一个merchandise
// createMerchandise("testSalesforceRestfulApi", "2000", "20001"); // 测试restful 查询一个List结果集
/*List<Merchandise> list = getMerchandiseByName("testSalesforceRestfulApi");
for (Merchandise item : list) {
System.out.print(item.getName() + "\t");
System.out.print(item.getPrice() + "\t");
System.out.println(item.getQuantity() + "\t");
}*/ //删除一个Merchandise
//deleteMerchandise("testSalesforceRestfulApi");
} public static void deleteMerchandise(String name) {
if (isAccessable()) {
HttpClient client = HttpClientBuilder.create().build();
String url = baseUri + "/deleteMerchandise/" + name;
HttpDelete delete = new HttpDelete(url);
delete.addHeader(oauthHeader);
delete.addHeader(prettyPrintHeader);
HttpResponse response = null;
try {
response = client.execute(delete);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
System.out.println("Deleted the goods successfully.");
} else {
System.out.println("goods delete NOT successful. Status code is " + statusCode);
}
delete.releaseConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* distinguish whether can access sfdc or not
*
* @return
*/
private static boolean isAccessable() {
HttpClient httpClient = HttpClientBuilder.create().build();
// Assemble the login request URL
String loginURL = LOGINURL + GRANTSERVIVE + "&client_id=" + CLIENTID + "&client_secret=" + CLIENTSECRET
+ "&username=" + USERNAME + "&password=" + PASSWORD; // Login requests must be POSTs
HttpPost httpPost = new HttpPost(loginURL);
HttpResponse response = null;
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException cpException) {
cpException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
// verify response is HTTP OK
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("Error authenticating to Force.com:" + statusCode);
return false;
}
String getResult = null;
try {
getResult = EntityUtils.toString(response.getEntity());
} catch (ParseException | IOException e) {
e.printStackTrace();
}
JSONObject jsonObject = null;
String loginAccessToken = null;
String loginInstanceUri = null;
try {
jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
loginAccessToken = jsonObject.getString("access_token");
loginInstanceUri = jsonObject.getString("instance_url");
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
baseUri = loginInstanceUri + REST_ENDPOINT + "/Merchandise";
oauthHeader = new BasicHeader("Authorization", "Bearer " + loginAccessToken);
System.out.println("oauthHeader1:" + oauthHeader);
System.out.println(response.getStatusLine());
System.out.println("Successful login");
System.out.println("instance URL:" + loginInstanceUri);
System.out.println("access token/sessing ID:" + loginAccessToken);
System.out.println("baseUri:" + baseUri);
return true;
} /**
* httpGet請求RESTful
*
* @param name
* @return
*/
public static List<Merchandise> getMerchandiseByName(String name) {
if (isAccessable()) {
String uri = baseUri + "/getMerchandiseByName?name=" + name;
System.out.println(uri);
HttpClient client = HttpClientBuilder.create().build();
HttpGet get = new HttpGet(uri);
get.setHeader(oauthHeader);
get.setHeader(prettyPrintHeader); try {
HttpResponse response = client.execute(get);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
List<Merchandise> merchandiseList = new ArrayList<Merchandise>();
String response_string = EntityUtils.toString(response.getEntity());
System.out.println("response_string:" + response_string);
JSONArray jsonArray = new JSONArray(response_string);
JSONObject jsonObject = null;
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
Merchandise item = new Merchandise();
if (jsonObject != null) {
item.setName(jsonObject.getString("Name"));
item.setPrice(jsonObject.getDouble("Price__c"));
item.setQuantity(jsonObject.getInt("Quantity__c"));
}
merchandiseList.add(item);
}
get.releaseConnection();
return merchandiseList;
} else {
get.releaseConnection();
return null;
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
return null; } /**
* httpPost請求 call restful api to create a merchandise return merchandise Id
*
* @param name
* @param price
* @param quantity
*/
public static void createMerchandise(String name, String price, String quantity) {
try {
if (isAccessable()) {
String uri = baseUri + "/insertMerchandise";
System.out.println(uri);
JSONObject merchandise = new JSONObject();
merchandise.put("name", name);
merchandise.put("price", price);
merchandise.put("quantity", quantity);
System.out.println("JSON for merchandises record to be insert:\n" + merchandise.toString());
// Construct the objects needed for the request
HttpClient httpClient = HttpClientBuilder.create().build();
;
System.out.println("oauthHeader" + oauthHeader);
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
httpPost.addHeader("encoding", "UTF-8");
// The message we are going to post
StringEntity body = new StringEntity(merchandise.toString(1));
System.out.println(merchandise.toString(1));
body.setContentType("application/json");
httpPost.setEntity(body); // Make the request
HttpResponse response = httpClient.execute(httpPost);
System.out.println("response: " + response.toString());
// Process the results
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("status code: " + statusCode);
if (statusCode == HttpStatus.SC_OK) {
String response_String = EntityUtils.toString(response.getEntity());
if (response_String != null) {
System.out.println("New Merchandise id from response:" + response_String);
}
} else {
System.out.println("Insertion unsuccessful.Status code returned is" + statusCode);
}
httpPost.releaseConnection();
}
} catch (JSONException e) {
System.out.println("Issue creating JSON or processing results");
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
} } }
下边是在JAVA的main方法中的测试结果
public static void main(String[] args) {
// 测试restful 创建一个merchandise
// createMerchandise("testSalesforceRestfulApi", "2000", "20001"); // 测试restful 查询一个List结果集
/*List<Merchandise> list = getMerchandiseByName("testSalesforceRestfulApi");
for (Merchandise item : list) {
System.out.print(item.getName() + "\t");
System.out.print(item.getPrice() + "\t");
System.out.println(item.getQuantity() + "\t");
}*/ //删除一个Merchandise
//deleteMerchandise("testSalesforceRestfulApi");
}
1、创建
oauthHeader1:Authorization: Bearer 00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
HTTP/1.1 200 OK
Successful login
instance URL:https://ap4.salesforce.com
access token/sessing ID:00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
baseUri:https://ap4.salesforce.com/services/apexrest/Merchandise
https://ap4.salesforce.com/services/apexrest/Merchandise/insertMerchandise
JSON for merchandises record to be insert:
{"quantity":"20001","price":"2000","name":"testSalesforceRestfulApi"}
oauthHeaderAuthorization: Bearer 00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
{
"quantity": "20001",
"price": "2000",
"name": "testSalesforceRestfulApi"
}
response: HttpResponseProxy{HTTP/1.1 200 OK [Date: Sat, 18 Mar 2017 10:46:28 GMT, X-Content-Type-Options: nosniff, X-XSS-Protection: 1; mode=block, Content-Security-Policy: reflected-xss block;report-uri /_/ContentDomainCSPNoAuth?type=xss, Content-Security-Policy: referrer origin-when-cross-origin, Set-Cookie: BrowserId=zDGh-qaEQOK5dJ9CGjk37A;Path=/;Domain=.salesforce.com;Expires=Wed, 17-May-2017 10:46:28 GMT, Expires: Thu, 01 Jan 1970 00:00:00 GMT, Content-Type: application/json;charset=UTF-8, Vary: Accept-Encoding, Transfer-Encoding: chunked] org.apache.http.client.entity.DecompressingEntity@77e9807f}
status code: 200
New Merchandise id from response:"a026F00000w1byFQAQ"
2、查询一个List结果
oauthHeader1:Authorization: Bearer 00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
HTTP/1.1 200 OK
Successful login
instance URL:https://ap4.salesforce.com
access token/sessing ID:00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
baseUri:https://ap4.salesforce.com/services/apexrest/Merchandise
https://ap4.salesforce.com/services/apexrest/Merchandise/getMerchandiseByName?name=testSalesforceRestfulApi
response_string:[ {
"attributes" : {
"type" : "Merchandise__c",
"url" : "/services/data/v39.0/sobjects/Merchandise__c/a026F00000w1byFQAQ"
},
"Quantity__c" : 20001,
"Price__c" : 2000.00,
"Name" : "testSalesforceRestfulApi",
"Id" : "a026F00000w1byFQAQ"
} ]
testSalesforceRestfulApi 2000.0 20001
3、删除一个Merchandise通过HttpDelete
oauthHeader1:Authorization: Bearer 00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
HTTP/1.1 200 OK
Successful login
instance URL:https://ap4.salesforce.com
access token/sessing ID:00D6F000000DauB!AQEAQFTLrj3cDuNoJuemXGm4HES9HvyHV9uJZk_TQVGAUd_oi5ZmxRWWYSsKB5Ibp8AOIALrR51laxO4jSnndv5.bsRk6G3.
baseUri:https://ap4.salesforce.com/services/apexrest/Merchandise
Deleted the goods successfully.
该JAVA项目中需要的jar包
73、salesforce通过JAVA来Call在salesforce中已经写好的Restful处理接口的更多相关文章
- 第73节:Java中的HTTPServletReauest和HTTPServletResponse
第73节:Java中的HTTPServletReauest和HTTPServletResponse HTTP协议 客户端与服务器端通讯的一种规则. request: 请求行 请求头 请求体 respo ...
- Salesforce 开发整理(九) 开发中使用的一些小技巧汇总[持续更新]
1.查询一个对象下所有字段 当需要查询一个对象所有字段进行复制或其他操作,可以使用一段拼接的语句来查询 String query = 'select '; for(String fieldApi : ...
- Java对比两个数据库中的表和字段,写个冷门的东西
Java对比两个数据库中的表和字段,写个冷门的东西 转载的 来源网络 目前所在的项目组距离下个版本上线已经很近了,就面临了一个问题:开发人员在开发库上根据需要增加数据表.数据字段.或者变更了字段类型或 ...
- JDBC Java 程序从 MySQL 数据库中读取数据,并备份到 xml 文档中
MySQL 版本:Server version: 5.7.17-log MySQL Community Server (GPL) 相关内容:JDBC Java 程序从 MySQL 数据库中读取数据,并 ...
- Atitit.java c#.net php项目中的view复用(jsp,aspx,php的复用)
Atitit.java c#.net php项目中的view复用(jsp,aspx,php的复用) 1.1. Keyword1 1.2. 前言1 2. Java项目使用.Net的aspx页面view1 ...
- Java 8中一些常用的全新的函数式接口
这一篇属于菜鸟级博客,只是介绍了一些在Java 8中新出现的一些很有用的接口,通过一些简单的例子加以说明,没有深入地阐述. 函数式接口 什么是函数式接口? 函数式接口,@FunctionalInter ...
- HttpTool.java(在java tool util工具类中已存在) 暂保留
HttpTool.java 该类为java源生态的http 请求工具,不依赖第三方jar包 ,即插即用. package kingtool; import java.io.BufferedReader ...
- Java 项目JDBC 链接数据库中会出现的错误
1.出现的地方 package com.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql ...
- java 11-8 在大串中查找小串的案例
1.统计大串中小串出现的次数 举例: 在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun& ...
随机推荐
- 富文本编辑器——百度UEditor插件安装教程
一.使用环境 Win7 Eclipse jettty9 chrome 二.下载百度UEditor插件 1.下载地址:http://ueditor.baidu.com/website/download. ...
- java ee项目用gradle依赖打包
plugins { id 'java' id 'eclipse' id 'idea' id 'application' } //mainClassName = ConnectionElasticSea ...
- WebBrowser元素定位的常用方法
在delphi中想要使用WebBrowser控件,需要一了解一些浏览器和网站制作的知识.操作元素(增删改查).需要提前了解HTML DOM.
- 小程序报错 Please do not register multiple Pages in undefined.js
在pages下面建了一个新页面的文件夹,但是没有在page.json里面注册,所以报了这个bug,注册一下就行了.
- Java反射实现Servlet处理多个请求--server分发
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.serv ...
- PAT_A1085#Perfect Sequence
Source: PAT A1085 Perfect Sequence (25 分) Description: Given a sequence of positive integers and ano ...
- python 装饰器 第七步:带有参数的装饰器
#第七步:带有参数的装饰器 #两个基本函数用同一个装饰器装饰 def outer(arg): print(arg) #这是装饰器的代码 def kuozhan(func): print(func) # ...
- Redis 系列(04-2)Redis原理 - 内存回收
目录 Redis 系列(04-2)Redis原理 - 内存回收 Redis 系列目录 1. 过期策略 1.1 定时过期(主动淘汰) 1.2 惰性过期(被动淘汰) 1.3 定期过期 2. 淘汰策略 2. ...
- go 学习之函数
个人把go函数理解分三种: 1.普通函数 普通函数声明: func name(parameter-list) (result-list) { body} package main import &qu ...
- Sublime Text3怎样在Deepin中配置CTags插件
首先是要安装好Package Control,然后装插件CTags,这个时候在文件中右键已经能够出现Navigate to Definition菜单项了.然而,如果没有装CTags这个软件还是没用,所 ...