Salesforce作为REST Service供java访问

有的时候我们需要在其他平台上获取sfdc端的数据,比如做android项目需要访问sfdc数据,那样就需要Salesforce作为Service,java端通过http获取并对数据进行相关操作。步骤如下:

1)新建一个App,然后创建Connected App:

setup->Build->Create->Apps.先new一个app,正常new完以后new一个Connected App,设置Enable OAuth Settings为true,截图如下所示:

910966-20160625184936703-394330774.png

java访问sfdc 的Service的时候需要用到Consumer Key以及Consumer Secret这两项。

3995993195c232ff22493c0e8d08acc8f45.jpg

注意:允许用户要选择管理员批准的用户为预先授权以及选择解除IP限制。

2)sfdc端rest service构建:这里我们以Goods__c进行操作,主要方法有添加一条Goods,通过Id获取Goods,通过PageNumber获取指定条数开始的Goods数据,修改一条Goods以及删除一条Goods。

这里对常用的注解进行解释:

  1.@RestResource:曝光此类作为REST资源;

  2.@HttpGet:曝光方法作为REST资源,当有Http get请求发送时,此注解对应的方法会被执行;

  3.@HttpPost:Http post 请求发送时,此注解对应的方法会被执行;

  4.@HttpDelete:当有Http delete请求发送时,此注解对应的方法会被执行;

  5.@HttpPut:当有Http put请求发送时,此注解对应的方法会被执行;

  6.@HttpPatch:当有Http patch请求发送时,此注解对应的方法会被执行。

因为http有请求时按照请求方式来对应相关方法,所以一个类中上述标签只能存在一个,即不能存在两个方法标注@HttpRequest等。

/*
* 使用salesforce通过REST方式作为webservice,需要以下几点:
* 1.类和方法需要global,方法需要静态
* 2.类需要通过RestResource(UrlMapping='/page/*')注解声明
* 3.@HttpGet和@HttpDelete不能有形参,可以通过URL?param或者URL/param方式传过来参数
*/
@RestResource(UrlMapping='/Goods/*')
global class GoodsRESTController {
    global static final Integer PAGE_SIZE = 20;
    @HttpGet
    global static List<Goods__c> getGoodsByIdOrGoodsList() {
        RestRequest request = RestContext.request;
        // grab the goodsId 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;
        String goodsId = request.params.get('goodsId');
        String fetchSql;
        if(goodsId != null) {
            fetchSql = 'SELECT CreatedById, CreatedDate, IsDeleted, Name,' +
            ' GoodsBrand__c, GoodsCostPrice__c, GoodsDescribe__c, GoodsName__c,' +
            ' GoodsPrice__c, GoodsProfit__c, LastActivityDate, LastModifiedById,' +
            ' LastModifiedDate, No__c, OwnerId, Id FROM Goods__c' +
            ' where Id = :goodsId';
        } else {
            fetchSql = 'SELECT CreatedById, CreatedDate, IsDeleted, Name,' +
            ' GoodsBrand__c, GoodsCostPrice__c, GoodsDescribe__c, GoodsName__c,' +
            ' GoodsPrice__c, GoodsProfit__c, LastActivityDate, LastModifiedById,' +
            ' LastModifiedDate, No__c, OwnerId, Id FROM Goods__c limit :PAGE_SIZE offset :offsetNumber';
        }
        List<Goods__c> goodsList = Database.query(fetchSql);
        return goodsList;
    }
    
    
    @HttpPost
    global static Id insertGoods(String goodsName,String goodsBrand,String goodsPrice,String goodsCostPrice,String goodsDescribe) {
        System.debug('---------goodsName-------------' + goodsName);
        Goods__c goods = new Goods__c();
        if(goodsPrice != null && goodsPrice.isNumeric()) {
            goods.GoodsPrice__c = Double.valueOf(goodsPrice);
        }
        if(goodsCostPrice != null && goodsCostPrice.isNumeric()) {
            goods.GoodsCostPrice__c = Double.valueOf(goodsCostPrice);
        }
        goods.GoodsName__c = goodsName;
        goods.GoodsDescribe__c = goodsDescribe;
        insert goods;
        return goods.Id;
    }
    
    @HttpDelete
    global static void deleteGoods() {
        RestRequest request = RestContext.request;
        String goodsId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Goods__c needDeleteGoods = [select Id from Goods__c where Id = :goodsId];
        if(needDeleteGoods != null) {
            delete needDeleteGoods;
        }
    }
    
    @HttpPut
    global static ID upsertGoods(String id,String goodsName,String goodsBrand,String goodsPrice,String goodsCostPrice,String goodsDescribe) {
        Goods__c goods = new Goods__c();
        goods.Id = id;
        goods.GoodsName__c = goodsName;
        goods.GoodsBrand__c = goodsBrand;
        goods.GoodsDescribe__c = goodsDescribe;
        if(goodsPrice != null && goodsPrice.isNumeric()) {
            goods.GoodsPrice__c = Double.valueOf(goodsPrice);
        }
        if(goodsCostPrice != null && goodsCostPrice.isNumeric()) {
            goods.GoodsCostPrice__c = Double.valueOf(goodsCostPrice);
        }
        upsert goods;
        return goods.Id;
    }

    @HttpPatch
    global static ID updateGoods() {
        RestRequest request = RestContext.request;
        String goodsId = request.requestURI.substring(
            request.requestURI.lastIndexOf('/')+1);
        Goods__c goods = [select Id from Goods__c where Id= :goodsId];
        // 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
        goods.GoodsName__c = String.valueOf(params.get('GoodsName__c'));
        goods.GoodsPrice__c = Double.valueOf(params.get('GoodsPrice__c'));
        goods.GoodsCostPrice__c = Double.valueOf(params.get('GoodsCostPrice__c'));
        update goods;
        return goods.Id;
    } 
    
    
    
}

测试自己写的方法可以在workbench中查看,使用salesforce账号登录workbench,https://workbench.developerforce.com/login.php.在这里可以测试一下getGoodsByIdOrGoodsList方法,想要测试其他方法可以参看最上面的链接自行测试。如下图所示:

910966-20160625220606063-1419472973.png

3)java端访问sfdc的REST Service

java端访问sfdc的REST Service之前需要做两部分,第一部分是下载Http client的jar包,第二部分是下载json的jar包。

1.Http client jar包下载:访问http://hc.apache.org/downloads.cgi 选择最新的jar包进行下载,下载后解压,在lib目录下位所需要的http client的jar包。

910966-20160625222116453-705552029.png

2.下载json的jar包:http://mvnrepository.com/artifact/org.json/json。可以选择下载最新的json下载后将json的jar和http client的jar放在一个文件夹下,比如我们现在放在桌面的jars文件夹下。

910966-20160625223324000-1488442437.png

接下来打开eclipse,jars目录下的jar包全都放在java项目里,然后开始代码访问阶段。

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class InvokeGoodsByRestViaSFDC {
     static final String USERNAME     = "你的salesforce账号";
     static final String PASSWORD     = "你的登录密码以及安全标识";
     static final String LOGINURL     = "https://login.salesforce.com";
     static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
     static final String CLIENTID     = "3MVG9pe2TCoA1Pf5QIj3FcPC_7ykIKqrJaxcbP4PEzsHw0UHAqhsVzxo4XPD1zqxTLmpJaCcfwp_TqE3IYjAG";
     static final String CLIENTSECRET = "05C0211E8A72E2F5ED8C5CD83952FC716141B692A4246529FC38C38731021E7E";//上图中的Consumer Secret
     private static String REST_ENDPOINT = "/services/apexrest" ;
     private static String baseUri;
     private static Header oauthHeader;
     private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
     
     private static boolean isAccessable() {
         HttpClient httpclient = HttpClientBuilder.create().build();
         String loginURL = LOGINURL +
                                         GRANTSERVICE +
                                           "&client_id=" + CLIENTID +
                                           "&client_secret=" + CLIENTSECRET +
                                           "&username=" + USERNAME +
                                            "&password=" + PASSWORD;
              HttpPost httpPost = new HttpPost(loginURL);
              System.out.println(loginURL);
              HttpResponse response = null;
              
              try {
                response = httpclient.execute(httpPost);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
              
             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 (IOException ioException) {
                // TODO Auto-generated catch block
                ioException.printStackTrace();
            }
             JSONObject jsonObject = null;
             String loginAccessToken = null;
             String loginInstanceUrl = null;
             try {
                jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
                loginAccessToken = jsonObject.getString("access_token");
                loginInstanceUrl = jsonObject.getString("instance_url");
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             baseUri = loginInstanceUrl + REST_ENDPOINT + "/account";
             oauthHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken) ;
             System.out.println("oauthHeader1: " + oauthHeader);
                     System.out.println(response.getStatusLine());
                      System.out.println("Successful login");
                      System.out.println("instance URL: "+loginInstanceUrl);
                      System.out.println("access token/session ID: "+loginAccessToken);
                      System.out.println("baseUri: "+ baseUri);        
                      return true;
     }
     
     public static void main(String[] args) {
        //InvokeGoodsByRestViaSFDC.createGoods("百度");
        // InvokeGoodsByRestViaSFDC.deleteAccount("yipan");
         //Account account=new Account();
         //account.setId("0010o00002Hdpsl");
         //account.setName("百度");
         //InvokeGoodsByRestViaSFDC.updateAccount(account);
         InvokeGoodsByRestViaSFDC. getAccountList();
    }

     public static void createGoods(String accountName) {
         try {
         if(isAccessable()) {
             String uri = baseUri + "/insertGoods";
             System.out.println(uri);
             JSONObject account = new JSONObject();
                account.put("accountName", accountName);
                System.out.println("JSON for account record to be insert:\n" + account.toString());
                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");
                StringEntity body = new StringEntity(account.toString(1),"UTF-8");
                body.setContentType("application/json");
                httpPost.setEntity(body);
                HttpResponse response = httpClient.execute(httpPost);
                System.out.print("response : " + response.toString());
                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 Account id from response: " + response_string);
                    }
                } else {
                     System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
                }
                httpPost.releaseConnection();
              }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException  e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (NullPointerException  e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }     
         
     }
     
     public static List<Account> getAccountList() {
            if (isAccessable()) {
                String uri = baseUri + "/getGoodsByIdOrGoodsList";
                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<Account> accountlist = new ArrayList<Account>();
                        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);
                            Account account = new Account();
                            if (jsonObject != null) {
                                account.setName(jsonObject.get("Name"));
                            }
                            accountlist.add(account);
                        }
                        get.releaseConnection();
                        return accountlist;
                    } 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;

        }
     
     public static void deleteAccount(String accountName) {
            if (isAccessable()) {
                HttpClient client = HttpClientBuilder.create().build();
                String url = baseUri + "/deleteGoods/" + accountName;
                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 accout successfully.");
                    } else {
                        System.out.println("delete NOT successful. Status code is " + statusCode);
                    }
                    delete.releaseConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
     
     
         
               public static void updateAccount(Account account) {
                   try {
                       if(isAccessable()) {
                           String uri = baseUri + "/updateGoods/"+account.getId();
                           System.out.println(account.getId());
                           JSONObject js = new JSONObject();
                           js.put("Name",account.getName());
                           System.out.println(account.getName());
                           org.apache.http.client.methods.HttpPatch httpPatch = new org.apache.http.client.methods.HttpPatch(uri);
                           HttpClient httpClient = HttpClientBuilder.create().build();
                           httpPatch.addHeader(oauthHeader);
                           httpPatch.addHeader(prettyPrintHeader);
                           StringEntity body = new StringEntity(js.toString(1),"UTF-8");
                           System.out.println(body);
                           body.setContentType("application/json");
                           httpPatch.setEntity(body);
                
                           //Make the request
                           HttpResponse response = httpClient.execute(httpPatch);
                
                           //Process the response
                           int statusCode = response.getStatusLine().getStatusCode();
                           if (statusCode == HttpStatus.SC_OK) {
                               System.out.println("Updated the goods successfully.");
                           } else {
                               System.out.println("update NOT successfully. Status code is " + statusCode);
                           }
                     }
                   }catch (JSONException e) {
                       System.out.println("Issue creating JSON or processing results");
                       e.printStackTrace();
                   } catch (IOException ioe) {
                       ioe.printStackTrace();
                  } catch (NullPointerException npe) {
                       npe.printStackTrace();
                   }
               }

}

测试一下

bee5f06907496dc603d40469629bcc15d44.jpg

 

转载于:https://my.oschina.net/u/3459265/blog/3037528

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值