日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

javaserver_如何在JavaServer Pages中使用Salesforce REST API

發(fā)布時間:2023/12/3 java 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 javaserver_如何在JavaServer Pages中使用Salesforce REST API 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

javaserver

摘要:本教程提供了一個JSP示例以及如何將其與Salesforce REST API集成。 我們將逐步完成創(chuàng)建外部客戶端以使用Force.com (同時使用HTTP(S)和JSON)管理數(shù)據(jù)的分步過程。

在此示例中,我將Mac OS X 10.9.2與Apache Tomcat 7服務(wù)器和Java 1.7一起使用。 Eclipse Java EE版是用于開發(fā)和測試的IDE。 本教程中給出的說明也應(yīng)適用于其他平臺的較小修改。

如果要訪問本教程中的整個示例代碼,則可以在以下位置訪問它: github.com/seethaa/force_rest_example

所有代碼已更新為可與httpclient 4.3庫一起使用。

什么是REST?

REST代表表象小號泰特貿(mào)易交接,并且是無狀態(tài)的客戶端-服務(wù)器通信協(xié)議通過HTTP。

為什么以及何時在Java中為JSP使用REST API

REST API非常適合需要大量交互并使用同步通信來傳輸數(shù)據(jù)的瀏覽器應(yīng)用程序。 Salesforce REST API為簡單的Web服務(wù)提供了與Force.com交互的編程接口,并支持XML和JSON格式。 Salesforce REST API非常適合移動應(yīng)用程序或動態(tài)網(wǎng)站,以在您的Web服務(wù)器上快速檢索或更新記錄。 雖然應(yīng)為BulkAPI保留批量記錄檢索,但此輕量級的REST API可以用于常見服務(wù)器頁面,這些頁面涉及快速更新和頻繁的用戶交互,例如更新單個用戶記錄。

設(shè)置您的開發(fā)帳戶和前提條件

您將需要以下內(nèi)容:

  • 轉(zhuǎn)到https://developer.salesforce.com/signup并注冊您的免費DE帳戶。 就本示例而言,即使您已經(jīng)有一個帳戶,我也建議注冊一個Developer Edition。 這樣可確保您在啟用了最新功能的情況下獲得干凈的環(huán)境。
  • Java應(yīng)用程序服務(wù)器。 我在Mac OS X和Eclipse上使用Apache Tomcat 7作為IDE創(chuàng)建了我的數(shù)據(jù)庫。 http://developer.salesforce.com/page/Force.com_IDE上還有一個免費的Eclipse插件,但本教程使用了原始的Eclipse設(shè)置。
  • 使用http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html在Tomcat服務(wù)器上配置SSL。 如果您在Eclipse中進(jìn)行開發(fā),請確保在Eclipse環(huán)境中的server.xml文件中添加連接器部分,例如: <Connector SSLEnabled="true" clientAuth="false" keystoreFile="/Users/seetha/.keystore" keystorePass="password" maxThreads="200" port="8443" protocol="HTTP/1.1" scheme="https" secure="true" sslProtocol="TLS"/>
  • 將所需的jar文件添加到WebContent / WEBINF / lib。 您將需要commons-codec-1.6.jar , httpclient4.3.3.jar , httpcore-4.3.2.jar , commons-logging-1.1.3.jar和java-json.jar 。 對于Eclipse,我還必須確保所有jar都已添加到構(gòu)建路徑中(右鍵單擊Project→Build Path→配置構(gòu)建路徑→選擇Libraries選項卡→單擊Add Jars→從WEBINF / lib文件夾中選擇Jar文件。
  • 創(chuàng)建一個連接的應(yīng)用程序

  • 返回Force.com DE,通過控制臺創(chuàng)建一個新的Connected App。 單擊設(shè)置→構(gòu)建→創(chuàng)建→應(yīng)用程序。 向下滾動到“已連接的應(yīng)用程序”部分,然后單擊“新建”按鈕。
    • 確保回調(diào)URL為http:// localhost:8080 / <your_app_context_path> / oauth / _callback

      (您可以通過返回Eclipse找到應(yīng)用程序上下文路徑:右鍵單擊Project→Properties→Web Project Settings→Context root)

    • 選中“啟用OAuth設(shè)置”復(fù)選框
    • 本教程所需的OAuth范圍(請參見圖1)是“訪問和管理數(shù)據(jù)(api)”和“通過Web提供對數(shù)據(jù)的訪問”(web),但是應(yīng)根據(jù)您的要求更改這些范圍。
    • 保存

      圖1:創(chuàng)建新的連接的應(yīng)用程序

  • 復(fù)制ClientID和Client Secret(參見圖2),因為這兩個都將在下一步中使用。

    圖2:具有用戶密鑰和機密的連接的應(yīng)用程序示例

    認(rèn)證方式

    需要將三個文件導(dǎo)入到您的JSP項目中,如下所示:

    index.html

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html? charset=UTF-8"> <title>REST/OAuth Example</title> </head> <body><script type="text/javascript" language="javascript">if (location.protocol != "https:") {document.write("OAuth will not work correctly from plain http. "+ "Please use an https URL.")?} else {document.write("<a href=\"oauth\">Run Connected App demo via REST/OAuth.</a>")?}</script> </body> </html>

    OAuthConnectedApp.java

    import java.io.IOException? import java.io.InputStream? import java.io.UnsupportedEncodingException? import java.net.URLEncoder? import java.util.ArrayList? import java.util.List?import javax.servlet.ServletException? import javax.servlet.annotation.WebInitParam? import javax.servlet.annotation.WebServlet? import javax.servlet.http.HttpServlet? import javax.servlet.http.HttpServletRequest? import javax.servlet.http.HttpServletResponse?import org.apache.http.Consts? import org.apache.http.HttpEntity? import org.apache.http.NameValuePair? import org.apache.http.client.entity.UrlEncodedFormEntity? import org.apache.http.client.methods.CloseableHttpResponse? import org.apache.http.client.methods.HttpPost? import org.apache.http.impl.client.CloseableHttpClient? import org.apache.http.impl.client.HttpClients? import org.apache.http.message.BasicNameValuePair?import org.json.JSONException? import org.json.JSONObject? import org.json.JSONTokener?@WebServlet(name = "oauth", urlPatterns = { "/oauth/*", "/oauth" }, initParams = { // clientId is 'Consumer Key' in the Remote Access UI //**Update with your own Client ID @WebInitParam(name = "clientId", value = "3MVG9JZ_r.QzrS7jzujCYrebr8kajDEcjXQLXnV9nGU6PaxOjuOi_n8EcUf0Ix9qqk1lYCa4_Jaq7mpqxi2YT"), // clientSecret is 'Consumer Secret' in the Remote Access UI //**Update with your own Client Secret @WebInitParam(name = "clientSecret", value = "2307033558641049067"), // This must be identical to 'Callback URL' in the Remote Access UI //**Update with your own URI @WebInitParam(name = "redirectUri", value = "http://localhost:8080/force_rest_example/oauth/_callback"), @WebInitParam(name = "environment", value = "https://login.salesforce.com"), })/** * Servlet parameters * @author seetha * */ public class OAuthConnectedApp extends HttpServlet {private static final long serialVersionUID = 1L?private static final String ACCESS_TOKEN = "ACCESS_TOKEN"?private static final String INSTANCE_URL = "INSTANCE_URL"?private String clientId = null?private String clientSecret = null?private String redirectUri = null?private String environment = null?private String authUrl = null?private String tokenUrl = null?public void init() throws ServletException {clientId = this.getInitParameter("clientId")?clientSecret = this.getInitParameter("clientSecret")?redirectUri = this.getInitParameter("redirectUri");environment = this.getInitParameter("environment")?try {authUrl = environment+ "/services/oauth2/authorize?response_type=code&client_id="+ clientId + "&redirect_uri="+ URLEncoder.encode(redirectUri, "UTF-8")?}catch (UnsupportedEncodingException e) {throw new ServletException(e)?}tokenUrl = environment + "/services/oauth2/token"?}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String accessToken = (String) request.getSession().getAttribute(ACCESS_TOKEN)?//System.out.println("calling doget")?if (accessToken == null) {String instanceUrl = null?if (request.getRequestURI().endsWith("oauth")) {// we need to send the user to authorizeresponse.sendRedirect(authUrl)?return?}else {System.out.println("Auth successful - got callback")?String code = request.getParameter("code")?// Create an instance of HttpClient.CloseableHttpClient httpclient = HttpClients.createDefault()?try{// Create an instance of HttpPost.HttpPost httpost = new HttpPost(tokenUrl)?// Adding all form parameters in a List of type NameValuePairList<NameValuePair> nvps = new ArrayList<NameValuePair>()?nvps.add(new BasicNameValuePair("code", code))?nvps.add(new BasicNameValuePair("grant_type","authorization_code"))?nvps.add(new BasicNameValuePair("client_id", clientId))?nvps.add(new BasicNameValuePair("client_secret", clientSecret))?nvps.add(new BasicNameValuePair("redirect_uri", redirectUri))?httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8))?// Execute the request.CloseableHttpResponse closeableresponse=httpclient.execute(httpost)?System.out.println("Response Statusline:"+closeableresponse.getStatusLine())?try {// Do the needful with entity.HttpEntity entity = closeableresponse.getEntity()?InputStream rstream = entity.getContent()?JSONObject authResponse = new JSONObject(new JSONTokener(rstream))?accessToken = authResponse.getString("access_token")?instanceUrl = authResponse.getString("instance_url")?} catch (JSONException e) {// TODO Auto-generated catch block e.printStackTrace()?e.printStackTrace()?} finally {// Closing the responsecloseableresponse.close()?}} finally {httpclient.close()?}}// Set a session attribute so that other servlets can get the access tokenrequest.getSession().setAttribute(ACCESS_TOKEN, accessToken)?// We also get the instance URL from the OAuth response, so set it in the session toorequest.getSession().setAttribute(INSTANCE_URL, instanceUrl)?}response.sendRedirect(request.getContextPath() + "/ConnectedAppREST")?}}

    ConnectedAppREST.java

    import java.io.IOException? import java.io.InputStream? import java.io.PrintWriter? import java.net.URISyntaxException? import java.util.Iterator?import javax.servlet.ServletException? import javax.servlet.annotation.WebServlet? import javax.servlet.http.HttpServlet? import javax.servlet.http.HttpServletRequest? import javax.servlet.http.HttpServletResponse?import org.apache.http.HttpEntity? import org.apache.http.HttpStatus? import org.apache.http.client.methods.CloseableHttpResponse? 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.client.utils.URIBuilder? import org.apache.http.entity.ContentType? import org.apache.http.entity.StringEntity? import org.apache.http.impl.client.CloseableHttpClient? import org.apache.http.impl.client.HttpClients?import org.json.JSONArray? import org.json.JSONException? import org.json.JSONObject? import org.json.JSONTokener?@WebServlet(urlPatterns = { "/ConnectedAppREST" }) /** * Demo for Connect App/REST API * @author seetha * */ public class ConnectedAppREST extends HttpServlet {private static final long serialVersionUID = 1L?private static final String ACCESS_TOKEN = "ACCESS_TOKEN"?private static final String INSTANCE_URL = "INSTANCE_URL"?private void showAccounts(String instanceUrl, String accessToken,PrintWriter writer) throws ServletException, IOException {CloseableHttpClient httpclient = HttpClients.createDefault()?HttpGet httpGet = new HttpGet()?//add key and valuehttpGet.addHeader("Authorization", "OAuth " + accessToken)?try {URIBuilder builder = new URIBuilder(instanceUrl+ "/services/data/v30.0/query")?builder.setParameter("q", "SELECT Name, Id from Account LIMIT 100")?httpGet.setURI(builder.build())?CloseableHttpResponse closeableresponse = httpclient.execute(httpGet)?System.out.println("Response Status line :" + closeableresponse.getStatusLine())?if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// Now lets use the standard java json classes to work with the resultstry {// Do the needful with entity.HttpEntity entity = closeableresponse.getEntity()?InputStream rstream = entity.getContent()?JSONObject authResponse = new JSONObject(new JSONTokener(rstream))?System.out.println("Query response: " + authResponse.toString(2))?writer.write(authResponse.getInt("totalSize") + " record(s) returned\n\n")?JSONArray results = authResponse.getJSONArray("records")?for (int i = 0? i < results.length()? i++) {writer.write(results.getJSONObject(i).getString("Id")+ ", "+ results.getJSONObject(i).getString("Name")+ "\n")?}writer.write("\n")?}catch (JSONException e) {e.printStackTrace()?throw new ServletException(e)?}}} catch (URISyntaxException e1) {// TODO Auto-generated catch blocke1.printStackTrace()?} finally {httpclient.close()?}}private String createAccount(String name, String instanceUrl,String accessToken, PrintWriter writer) throws ServletException, IOException {String accountId = null?CloseableHttpClient httpclient = HttpClients.createDefault()?JSONObject account = new JSONObject()?try {account.put("Name", name)?}catch (JSONException e) {e.printStackTrace()?throw new ServletException(e)?}HttpPost httpost = new HttpPost(instanceUrl+ "/services/data/v30.0/sobjects/Account/")?httpost.addHeader("Authorization", "OAuth " + accessToken)?StringEntity messageEntity = new StringEntity( account.toString(), ContentType.create("application/json"))?httpost.setEntity(messageEntity)?// Execute the request.CloseableHttpResponse closeableresponse = httpclient.execute(httpost)?System.out.println("Response Status line :" + closeableresponse.getStatusLine())?try {writer.write("HTTP status " + closeableresponse.getStatusLine().getStatusCode() + " creating account\n\n")?if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {try {// Do the needful with entity.HttpEntity entity = closeableresponse.getEntity()?InputStream rstream = entity.getContent()?JSONObject authResponse = new JSONObject(new JSONTokener(rstream))?System.out.println("Create response: " + authResponse.toString(2))?if (authResponse.getBoolean("success")) {accountId = authResponse.getString("id")?writer.write("New record id " + accountId + "\n\n")?}} catch (JSONException e) {e.printStackTrace()?// throw new ServletException(e)?}}}finally {httpclient.close()?}return accountId?}private void showAccount(String accountId, String instanceUrl,String accessToken, PrintWriter writer) throws ServletException, IOException {CloseableHttpClient httpclient = HttpClients.createDefault()?HttpGet httpGet = new HttpGet()?//add key and valuehttpGet.addHeader("Authorization", "OAuth " + accessToken)?try {URIBuilder builder = new URIBuilder(instanceUrl + "/services/data/v30.0/sobjects/Account/" + accountId)?httpGet.setURI(builder.build())?//httpclient.execute(httpGet)?CloseableHttpResponse closeableresponse = httpclient.execute(httpGet)?System.out.println("Response Status line :" + closeableresponse.getStatusLine())?if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {try {// Do the needful with entity.HttpEntity entity = closeableresponse.getEntity()?InputStream rstream = entity.getContent()?JSONObject authResponse = new JSONObject(new JSONTokener(rstream))?System.out.println("Query response: " + authResponse.toString(2))?writer.write("Account content\n\n")?Iterator iterator = authResponse.keys()?while (iterator.hasNext()) {String key = (String) iterator.next()?Object obj = authResponse.get(key)?String value = null?if (obj instanceof String) {value = (String) obj?}writer.write(key + ":" + (value != null ? value : "") + "\n")?}writer.write("\n")?} catch (JSONException e) {e.printStackTrace()?throw new ServletException(e)?}}}catch (URISyntaxException e1) {// TODO Auto-generated catch blocke1.printStackTrace()?} finally {httpclient.close()?}}private void updateAccount(String accountId, String newName, String city, String instanceUrl, String accessToken, PrintWriter writer) throws ServletException, IOException {CloseableHttpClient httpclient = HttpClients.createDefault()?JSONObject update = new JSONObject()?try {update.put("Name", newName)?update.put("BillingCity", city)?}catch (JSONException e) {e.printStackTrace()?throw new ServletException(e)?}HttpPost httpost = new HttpPost(instanceUrl + "/services/data/v30.0/sobjects/Account/" +accountId+"?_HttpMethod=PATCH")?httpost.addHeader("Authorization", "OAuth " + accessToken)?StringEntity messageEntity = new StringEntity( update.toString(), ContentType.create("application/json"))?httpost.setEntity(messageEntity)?// Execute the request.CloseableHttpResponse closeableresponse = httpclient.execute(httpost)? System.out.println("Response Status line :" + closeableresponse.getStatusLine())?try {writer.write("HTTP status " + closeableresponse.getStatusLine().getStatusCode() + " updating account " + accountId + "\n\n")?} finally {httpclient.close()?}}private void deleteAccount(String accountId, String instanceUrl, String accessToken, PrintWriter writer) throws IOException {CloseableHttpClient httpclient = HttpClients.createDefault()?HttpDelete delete = new HttpDelete(instanceUrl + "/services/data/v30.0/sobjects/Account/" + accountId)?delete.setHeader("Authorization", "OAuth " + accessToken)?// Execute the request.CloseableHttpResponse closeableresponse = httpclient.execute(delete)?System.out.println("Response Status line :" + closeableresponse.getStatusLine())?try {writer.write("HTTP status " + closeableresponse.getStatusLine().getStatusCode() + " deleting account " + accountId + "\n\n")?} finally {delete.releaseConnection()?}}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse* response)*/@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {PrintWriter writer = response.getWriter()?String accessToken = (String) request.getSession().getAttribute( ACCESS_TOKEN)?String instanceUrl = (String) request.getSession().getAttribute( INSTANCE_URL)?if (accessToken == null) {writer.write("Error - no access token")?return?}writer.write("We have an access token: " + accessToken + "\n" + "Using instance " + instanceUrl + "\n\n")?showAccounts(instanceUrl, accessToken, writer)?String accountId = createAccount("My New Org", instanceUrl, accessToken, writer)?if (accountId == null) {System.out.println("Account ID null")?}showAccount(accountId, instanceUrl, accessToken, writer)?showAccounts(instanceUrl, accessToken, writer)?updateAccount(accountId, "My New Org, Inc", "San Francisco", instanceUrl, accessToken, writer)?showAccount(accountId, instanceUrl, accessToken, writer)?deleteAccount(accountId, instanceUrl, accessToken, writer)?showAccounts(instanceUrl, accessToken, writer)?}}
  • 更改OAuthConnectedApp.java,以根據(jù)Connected App配置替換Client ID,Client Secret和Callback URI字段。
  • 在Eclipse(請參見圖3)中或從外部啟動Tomcat服務(wù)器,并導(dǎo)航到https:// localhost:8443 / <your_app_context_path> /

    圖3:在Eclipse中運行Tomcat服務(wù)器


    圖4:檢索對象屏幕

  • 除非通過HTTPS,否則單擊上面的鏈接(請參見圖4)將不起作用,并且必須將SSL配置為Tomcat的端點。

    如果所有配置都正確完成,您應(yīng)該會看到一個salesforce.com登錄屏幕(請參見圖5)。 繼續(xù)并使用您的salesforce.com憑據(jù)登錄以授權(quán)您的Web應(yīng)用程序訪問資源。

    圖5:OAuth的Salesforce.com登錄屏幕

  • 登錄將允許ConnectedAppREST演示執(zhí)行創(chuàng)建,顯示,更新和刪除記錄的方法(請參見圖6)。

    圖6:Connected App REST演示的輸出

  • *提示和警告

  • 確保您擁有一個Developer Edition(DE)帳戶,因為Professional,Enterprise,Developer等之間存在細(xì)微差別。DeveloperEdition是免費的,并且不會過期(除非一年后未使用)。
  • OAuthConnectedApp.java中的回調(diào)URL必須與添加到連接的應(yīng)用程序的URL相同。
  • 如果收到HTTP 403錯誤,則表示正在訪問您請求的資源“被禁止”。 檢查您用來訪問的用戶名/帳戶是否具有適當(dāng)?shù)臋?quán)限。
  • 確保index.html直接在WebContent目錄下。
  • 資源資源

    有關(guān)全面的設(shè)置或資源,請訪問: http : //developer.salesforce.com/en/mobile/resources

    參考資料

  • Force.com REST API開發(fā)人員指南 (PDF)
  • 使用Force.com REST API
  • 翻譯自: https://www.javacodegeeks.com/2014/06/how-to-use-salesforce-rest-api-with-your-javaserver-pages.html

    javaserver

    總結(jié)

    以上是生活随笔為你收集整理的javaserver_如何在JavaServer Pages中使用Salesforce REST API的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。