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 = "[email protected]";
    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] [email protected]}
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包

时间: 2024-10-12 23:15:44

73、salesforce通过JAVA来Call在salesforce中已经写好的Restful处理接口的相关文章

Java学习-040-级联删除目录中的文件、目录

之前在写应用模块,进行单元测试编码的时候,居然脑洞大开居然创建了一个 N 层的目录,到后来删除测试结果目录的时候,才发现删除不了了,提示目录过长无法删除.网上找了一些方法,也找了一些粉碎机,都没能达到想要的结果,我就简写了一个小应用,用于删除自己脑洞大开创建的级联目录.此小应用没有代码注释,也没有进行容错处理,请大家知悉!哈哈哈哈哈.....若发现有错误,也请告知,我会去修改订正,非常感谢! 闲话少述,直接上码了! 1 /** 2 * Aaron.ffp Inc. 3 * Copyright (

Java对比两个数据库中的表和字段,写个冷门的东西

Java对比两个数据库中的表和字段,写个冷门的东西 转载的 来源网络 目前所在的项目组距离下个版本上线已经很近了,就面临了一个问题:开发人员在开发库上根据需要增加数据表.数据字段.或者变更了字段类型或者字段长度等等. 由于时间比较紧迫,导致在开发过程中不可能一一把DDL数据库脚本记录下来,在比较大的项目中,比如我所在项目开发的系统大概包含了800张左右的表,字段上10000个的情况下,人工处理明显不可行,所以我们就得通过程序来判断比对,哪些是我们需要新增加的表,哪些是我们需要新增加的字段,哪些是

[Java Web]2\Web开发中的一些架构

1.企业开发架构: 企业平台开发大量采用B/S开发模式,不管采用何种动态Web实现手段,其操作形式都是一样的,其核心操作的大部分都是围绕着数据库进行的.但是如果使用编程语言进行数据库开发,要涉及很多诸如事务.安全等操作问题,所以现在开发往往要通过中间件进行过渡,即,程序运行在中间件上,并通过中间件进行操作系统的操作,而具体一些相关的处理,如事务.安全等完全由中间件来负责,这样程序员只要完成具体的功能开发即可. 2.Java EE架构: Java EE 是在 Java SE 的基础上构建的,.NE

java中IO写文件工具类

下面是一些根据常用java类进行组装的对文件进行操作的类,平时,我更喜欢使用Jodd.io中提供的一些对文件的操作类,里面的方法写的简单易懂. 其中jodd中提供的JavaUtil类中提供的方法足够我们使用,里面的方法写的非常简练,例如append,read等方法,封装更好,更符合面向对象, 这里面我写的一些方法可多都是模仿jodd,从里面进行抽取出来的. /** * 获取路径文件夹下的所有文件 * @param path * @return */ public static File[] ge

Java核心知识点学习----多线程中的阻塞队列,ArrayBlockingQueue介绍

1.什么是阻塞队列? 所谓队列,遵循的是先进先出原则(FIFO),阻塞队列,即是数据共享时,A在写数据时,B想读同一数据,那么就将发生阻塞了. 看一下线程的四种状态,首先是新创建一个线程,然后,通过start方法启动线程--->线程变为可运行可执行状态,然后通过数据产生共享,线程产生互斥---->线程状态变为阻塞状态---->阻塞状态想打开的话可以调用notify方法. 这里Java5中提供了封装好的类,可以直接调用然后构造阻塞状态,以保证数据的原子性. 2.如何实现? 主要是实现Blo

java 11-8 在大串中查找小串的案例

1.统计大串中小串出现的次数 举例: 在字符串"woaijavawozhenaijavawozhendeaijavawozhendehenaijavaxinbuxinwoaijavagun" 结果: java出现了5次 分析: 1.首先已经知道字符串 A:定义一个统计变量=0: B:在大串中查找小串是否存在,用 int indexOf(String str):返回指定字符在此字符串中第一次出现处的索引. a:如果返回的索引值是-1,则说明 大串中并不存在这个小串,输出统计变量 b:返回

java POI实现向Excel中插入图片

java POI实现向Excel中插入图片 标签: javapoiexcel 2014-03-05 08:59 9103人阅读 评论(4) 收藏 举报  分类: [JAVA开发]-----JavaScore(34)  版权声明:本文为博主原创文章,未经博主允许不得转载. 做Web开发免不了要与Excel打交道.今天老大给我一个任务-导出Excel.开始想的还是蛮简单的,无非就是查找,构建Excel,response下载即可.但是有一点不同,就是要加入图片,就是这个加入图片搞了好久.同时网络上确实

JAVA程序 写供别人调用的接口方法的时候 异常应该怎么处理?

要看出现的是哪种异常了.如果是使用某些定义好的函数,并且函数本身会产生异常处理方法一般两种:1.自己用try{}catch(){}语句捕获异常并处理.2.在定义接口的后面写上throw Exception.把异常抛出让使用接口的人处理异常.两种方法都可以.但如果是RuntimeException异常,那就是自己程序某些地方写错了,那你就必须找到并修改程序.JAVA程序 写供别人调用的接口方法的时候 异常应该怎么处理?,布布扣,bubuko.com

JAVA 处理时间 - java.sql.Date、java.util.Date与数据库中的Date字段的转换方法[转]

1.如何将java.util.Date转化为java.sql.Date? 转化: java.sql.Date sd; java.util.Date ud; //initialize the ud such as ud = new java.util.Date(); sd = new java.sql.Date(ud.getTime()); 2.如何将获取到的java.sql.Date转换为年-月-日输出 java.sql.Date sd; String dateTime = sd.toStrin