/** *使用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