├── salesforce_rest_api_1.java └── salesforce_rest_api_2.java /salesforce_rest_api_1.java: -------------------------------------------------------------------------------- 1 | package salesforce_rest; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.http.client.methods.HttpPost; 6 | import org.apache.http.client.HttpClient; 7 | import org.apache.http.impl.client.HttpClientBuilder; 8 | import org.apache.http.HttpResponse; 9 | import org.apache.http.HttpStatus; 10 | import org.apache.http.util.EntityUtils; 11 | import org.apache.http.client.ClientProtocolException; 12 | import org.json.JSONObject; 13 | import org.json.JSONTokener; 14 | import org.json.JSONException; 15 | 16 | public class Main { 17 | 18 | static final String USERNAME = "username@salesforce.com"; 19 | static final String PASSWORD = "passwordSecurityToken"; 20 | static final String LOGINURL = "https://login.salesforce.com"; 21 | static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password"; 22 | static final String CLIENTID = "ConsumerKeyFromSalesfoceConnectedApps"; 23 | static final String CLIENTSECRET = "ConsumerSecretFromSalesforceConnectedApps"; 24 | 25 | public static void main(String[] args) { 26 | 27 | HttpClient httpclient = HttpClientBuilder.create().build(); 28 | 29 | // Assemble the login request URL 30 | String loginURL = LOGINURL + 31 | GRANTSERVICE + 32 | "&client_id=" + CLIENTID + 33 | "&client_secret=" + CLIENTSECRET + 34 | "&username=" + USERNAME + 35 | "&password=" + PASSWORD; 36 | 37 | // Login requests must be POSTs 38 | HttpPost httpPost = new HttpPost(loginURL); 39 | HttpResponse response = null; 40 | 41 | try { 42 | // Execute the login POST request 43 | response = httpclient.execute(httpPost); 44 | } catch (ClientProtocolException cpException) { 45 | cpException.printStackTrace(); 46 | } catch (IOException ioException) { 47 | ioException.printStackTrace(); 48 | } 49 | 50 | // verify response is HTTP OK 51 | final int statusCode = response.getStatusLine().getStatusCode(); 52 | if (statusCode != HttpStatus.SC_OK) { 53 | System.out.println("Error authenticating to Force.com: "+statusCode); 54 | // Error is in EntityUtils.toString(response.getEntity()) 55 | return; 56 | } 57 | 58 | String getResult = null; 59 | try { 60 | getResult = EntityUtils.toString(response.getEntity()); 61 | } catch (IOException ioException) { 62 | ioException.printStackTrace(); 63 | } 64 | JSONObject jsonObject = null; 65 | String loginAccessToken = null; 66 | String loginInstanceUrl = null; 67 | try { 68 | jsonObject = (JSONObject) new JSONTokener(getResult).nextValue(); 69 | loginAccessToken = jsonObject.getString("access_token"); 70 | loginInstanceUrl = jsonObject.getString("instance_url"); 71 | } catch (JSONException jsonException) { 72 | jsonException.printStackTrace(); 73 | } 74 | System.out.println(response.getStatusLine()); 75 | System.out.println("Successful login"); 76 | System.out.println(" instance URL: "+loginInstanceUrl); 77 | System.out.println(" access token/session ID: "+loginAccessToken); 78 | 79 | // release connection 80 | httpPost.releaseConnection(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /salesforce_rest_api_2.java: -------------------------------------------------------------------------------- 1 | package salesforce_rest; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.InputStreamReader; 6 | import java.io.BufferedReader; 7 | 8 | import org.apache.http.Header; 9 | import org.apache.http.HttpResponse; 10 | import org.apache.http.client.HttpClient; 11 | import org.apache.http.client.methods.HttpDelete; 12 | import org.apache.http.client.methods.HttpGet; 13 | import org.apache.http.client.methods.HttpPost; 14 | import org.apache.http.entity.StringEntity; 15 | import org.apache.http.message.BasicHeader; 16 | import org.apache.http.impl.client.HttpClientBuilder; 17 | import org.apache.http.HttpStatus; 18 | import org.apache.http.util.EntityUtils; 19 | import org.apache.http.client.ClientProtocolException; 20 | import org.json.JSONObject; 21 | import org.json.JSONArray; 22 | import org.json.JSONTokener; 23 | import org.json.JSONException; 24 | 25 | public class Main { 26 | 27 | static final String USERNAME = "username@salesforce.com"; 28 | static final String PASSWORD = "passwordSecurityToken"; 29 | static final String LOGINURL = "https://login.salesforce.com"; 30 | static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password"; 31 | static final String CLIENTID = "ConsumerKeyFromSalesfoceConnectedApps"; 32 | static final String CLIENTSECRET = "ConsumerSecretFromSalesforceConnectedApps"; 33 | private static String REST_ENDPOINT = "/services/data" ; 34 | private static String API_VERSION = "/v32.0" ; 35 | private static String baseUri; 36 | private static Header oauthHeader; 37 | private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1"); 38 | private static String leadId ; 39 | private static String leadFirstName; 40 | private static String leadLastName; 41 | private static String leadCompany; 42 | 43 | public static void main(String[] args) { 44 | 45 | HttpClient httpclient = HttpClientBuilder.create().build(); 46 | 47 | // Assemble the login request URL 48 | String loginURL = LOGINURL + 49 | GRANTSERVICE + 50 | "&client_id=" + CLIENTID + 51 | "&client_secret=" + CLIENTSECRET + 52 | "&username=" + USERNAME + 53 | "&password=" + PASSWORD; 54 | 55 | // Login requests must be POSTs 56 | HttpPost httpPost = new HttpPost(loginURL); 57 | HttpResponse response = null; 58 | 59 | try { 60 | // Execute the login POST request 61 | response = httpclient.execute(httpPost); 62 | } catch (ClientProtocolException cpException) { 63 | cpException.printStackTrace(); 64 | } catch (IOException ioException) { 65 | ioException.printStackTrace(); 66 | } 67 | 68 | // verify response is HTTP OK 69 | final int statusCode = response.getStatusLine().getStatusCode(); 70 | if (statusCode != HttpStatus.SC_OK) { 71 | System.out.println("Error authenticating to Force.com: "+statusCode); 72 | // Error is in EntityUtils.toString(response.getEntity()) 73 | return; 74 | } 75 | 76 | String getResult = null; 77 | try { 78 | getResult = EntityUtils.toString(response.getEntity()); 79 | } catch (IOException ioException) { 80 | ioException.printStackTrace(); 81 | } 82 | 83 | JSONObject jsonObject = null; 84 | String loginAccessToken = null; 85 | String loginInstanceUrl = null; 86 | 87 | try { 88 | jsonObject = (JSONObject) new JSONTokener(getResult).nextValue(); 89 | loginAccessToken = jsonObject.getString("access_token"); 90 | loginInstanceUrl = jsonObject.getString("instance_url"); 91 | } catch (JSONException jsonException) { 92 | jsonException.printStackTrace(); 93 | } 94 | 95 | baseUri = loginInstanceUrl + REST_ENDPOINT + API_VERSION ; 96 | oauthHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken) ; 97 | System.out.println("oauthHeader1: " + oauthHeader); 98 | System.out.println("\n" + response.getStatusLine()); 99 | System.out.println("Successful login"); 100 | System.out.println("instance URL: "+loginInstanceUrl); 101 | System.out.println("access token/session ID: "+loginAccessToken); 102 | System.out.println("baseUri: "+ baseUri); 103 | 104 | // Run codes to query, isnert, update and delete records in Salesforce using REST API 105 | queryLeads(); 106 | createLeads(); 107 | updateLeads(); 108 | deleteLeads(); 109 | 110 | // release connection 111 | httpPost.releaseConnection(); 112 | } 113 | 114 | // Query Leads using REST HttpGet 115 | public static void queryLeads() { 116 | System.out.println("\n_______________ Lead QUERY _______________"); 117 | try { 118 | 119 | //Set up the HTTP objects needed to make the request. 120 | HttpClient httpClient = HttpClientBuilder.create().build(); 121 | 122 | String uri = baseUri + "/query?q=Select+Id+,+FirstName+,+LastName+,+Company+From+Lead+Limit+5"; 123 | System.out.println("Query URL: " + uri); 124 | HttpGet httpGet = new HttpGet(uri); 125 | System.out.println("oauthHeader2: " + oauthHeader); 126 | httpGet.addHeader(oauthHeader); 127 | httpGet.addHeader(prettyPrintHeader); 128 | 129 | // Make the request. 130 | HttpResponse response = httpClient.execute(httpGet); 131 | 132 | // Process the result 133 | int statusCode = response.getStatusLine().getStatusCode(); 134 | if (statusCode == 200) { 135 | String response_string = EntityUtils.toString(response.getEntity()); 136 | try { 137 | JSONObject json = new JSONObject(response_string); 138 | System.out.println("JSON result of Query:\n" + json.toString(1)); 139 | JSONArray j = json.getJSONArray("records"); 140 | for (int i = 0; i < j.length(); i++){ 141 | leadId = json.getJSONArray("records").getJSONObject(i).getString("Id"); 142 | leadFirstName = json.getJSONArray("records").getJSONObject(i).getString("FirstName"); 143 | leadLastName = json.getJSONArray("records").getJSONObject(i).getString("LastName"); 144 | leadCompany = json.getJSONArray("records").getJSONObject(i).getString("Company"); 145 | System.out.println("Lead record is: " + i + ". " + leadId + " " + leadFirstName + " " + leadLastName + "(" + leadCompany + ")"); 146 | } 147 | } catch (JSONException je) { 148 | je.printStackTrace(); 149 | } 150 | } else { 151 | System.out.println("Query was unsuccessful. Status code returned is " + statusCode); 152 | System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode()); 153 | System.out.println(getBody(response.getEntity().getContent())); 154 | System.exit(-1); 155 | } 156 | } catch (IOException ioe) { 157 | ioe.printStackTrace(); 158 | } catch (NullPointerException npe) { 159 | npe.printStackTrace(); 160 | } 161 | } 162 | 163 | // Create Leads using REST HttpPost 164 | public static void createLeads() { 165 | System.out.println("\n_______________ Lead INSERT _______________"); 166 | 167 | String uri = baseUri + "/sobjects/Lead/"; 168 | try { 169 | 170 | //create the JSON object containing the new lead details. 171 | JSONObject lead = new JSONObject(); 172 | lead.put("FirstName", "REST API"); 173 | lead.put("LastName", "Lead"); 174 | lead.put("Company", "asagarwal.com"); 175 | 176 | System.out.println("JSON for lead record to be inserted:\n" + lead.toString(1)); 177 | 178 | //Construct the objects needed for the request 179 | HttpClient httpClient = HttpClientBuilder.create().build(); 180 | 181 | HttpPost httpPost = new HttpPost(uri); 182 | httpPost.addHeader(oauthHeader); 183 | httpPost.addHeader(prettyPrintHeader); 184 | // The message we are going to post 185 | StringEntity body = new StringEntity(lead.toString(1)); 186 | body.setContentType("application/json"); 187 | httpPost.setEntity(body); 188 | 189 | //Make the request 190 | HttpResponse response = httpClient.execute(httpPost); 191 | 192 | //Process the results 193 | int statusCode = response.getStatusLine().getStatusCode(); 194 | if (statusCode == 201) { 195 | String response_string = EntityUtils.toString(response.getEntity()); 196 | JSONObject json = new JSONObject(response_string); 197 | // Store the retrieved lead id to use when we update the lead. 198 | leadId = json.getString("id"); 199 | System.out.println("New Lead id from response: " + leadId); 200 | } else { 201 | System.out.println("Insertion unsuccessful. Status code returned is " + statusCode); 202 | } 203 | } catch (JSONException e) { 204 | System.out.println("Issue creating JSON or processing results"); 205 | e.printStackTrace(); 206 | } catch (IOException ioe) { 207 | ioe.printStackTrace(); 208 | } catch (NullPointerException npe) { 209 | npe.printStackTrace(); 210 | } 211 | } 212 | 213 | // Update Leads using REST HttpPatch. We have to create the HTTPPatch, as it does not exist in the standard library 214 | // Since the PATCH method was only recently standardized and is not yet implemented in Apache HttpClient 215 | public static void updateLeads() { 216 | System.out.println("\n_______________ Lead UPDATE _______________"); 217 | 218 | //Notice, the id for the record to update is part of the URI, not part of the JSON 219 | String uri = baseUri + "/sobjects/Lead/" + leadId; 220 | try { 221 | //Create the JSON object containing the updated lead last name 222 | //and the id of the lead we are updating. 223 | JSONObject lead = new JSONObject(); 224 | lead.put("LastName", "Lead --UPDATED"); 225 | System.out.println("JSON for update of lead record:\n" + lead.toString(1)); 226 | 227 | //Set up the objects necessary to make the request. 228 | //DefaultHttpClient httpClient = new DefaultHttpClient(); 229 | HttpClient httpClient = HttpClientBuilder.create().build(); 230 | 231 | HttpPatch httpPatch = new HttpPatch(uri); 232 | httpPatch.addHeader(oauthHeader); 233 | httpPatch.addHeader(prettyPrintHeader); 234 | StringEntity body = new StringEntity(lead.toString(1)); 235 | body.setContentType("application/json"); 236 | httpPatch.setEntity(body); 237 | 238 | //Make the request 239 | HttpResponse response = httpClient.execute(httpPatch); 240 | 241 | //Process the response 242 | int statusCode = response.getStatusLine().getStatusCode(); 243 | if (statusCode == 204) { 244 | System.out.println("Updated the lead successfully."); 245 | } else { 246 | System.out.println("Lead update NOT successfully. Status code is " + statusCode); 247 | } 248 | } catch (JSONException e) { 249 | System.out.println("Issue creating JSON or processing results"); 250 | e.printStackTrace(); 251 | } catch (IOException ioe) { 252 | ioe.printStackTrace(); 253 | } catch (NullPointerException npe) { 254 | npe.printStackTrace(); 255 | } 256 | } 257 | 258 | // Extend the Apache HttpPost method to implement an HttpPatch 259 | private static class HttpPatch extends HttpPost { 260 | public HttpPatch(String uri) { 261 | super(uri); 262 | } 263 | 264 | public String getMethod() { 265 | return "PATCH"; 266 | } 267 | } 268 | 269 | // Update Leads using REST HttpDelete (We have to create the HTTPDelete, as it does not exist in the standard library.) 270 | public static void deleteLeads() { 271 | System.out.println("\n_______________ Lead DELETE _______________"); 272 | 273 | //Notice, the id for the record to update is part of the URI, not part of the JSON 274 | String uri = baseUri + "/sobjects/Lead/" + leadId; 275 | try { 276 | //Set up the objects necessary to make the request. 277 | HttpClient httpClient = HttpClientBuilder.create().build(); 278 | 279 | HttpDelete httpDelete = new HttpDelete(uri); 280 | httpDelete.addHeader(oauthHeader); 281 | httpDelete.addHeader(prettyPrintHeader); 282 | 283 | //Make the request 284 | HttpResponse response = httpClient.execute(httpDelete); 285 | 286 | //Process the response 287 | int statusCode = response.getStatusLine().getStatusCode(); 288 | if (statusCode == 204) { 289 | System.out.println("Deleted the lead successfully."); 290 | } else { 291 | System.out.println("Lead delete NOT successful. Status code is " + statusCode); 292 | } 293 | } catch (JSONException e) { 294 | System.out.println("Issue creating JSON or processing results"); 295 | e.printStackTrace(); 296 | } catch (IOException ioe) { 297 | ioe.printStackTrace(); 298 | } catch (NullPointerException npe) { 299 | npe.printStackTrace(); 300 | } 301 | } 302 | 303 | private static String getBody(InputStream inputStream) { 304 | String result = ""; 305 | try { 306 | BufferedReader in = new BufferedReader( 307 | new InputStreamReader(inputStream) 308 | ); 309 | String inputLine; 310 | while ( (inputLine = in.readLine() ) != null ) { 311 | result += inputLine; 312 | result += "\n"; 313 | } 314 | in.close(); 315 | } catch (IOException ioe) { 316 | ioe.printStackTrace(); 317 | } 318 | return result; 319 | } 320 | } 321 | --------------------------------------------------------------------------------