(IMPORTANT: This is an old blog post that shows how to execute java program from Eclipse IDE. If you would rather prefer to execute java program from VS Code, please navigate to this blog post instead)
How do you connect to Salesforce from an external application, say, for example Java? If you Google for the information, you will quickly learn that Salesforce provides different methods and different APIs. But what you will probably not find is a step-by-step guide teaching you exactly how to do it. In this blog post, I have stitched together a complete step-by-step instructions with screenshots on how to download, install, configure and use Salesforce REST API to connect from a java program and execute some basic transactions (query, insert, update, delete records). In less than 45 minutes, you will have a fully functional java program that will connect to Salesforce and execute transactions in Salesforce.
The guide includes downloading & installing necessary HttpClient and JSON frameworks that is required to work with Salesforce REST APIs. This is followed by referencing the JAR file in your java program, logging on to Salesforce from the java program, querying and manipulating data. Here is an overview of steps that needs to be completed and is covered in the guide
- Install Java
- Install Eclipse
- Install HttpClient
- Install JSON Framework
- Create Connected Apps in Salesforce
- Setup REST Environment in Java
- Create Java Program
- Execute Transactions using REST API
(Once you are done with this, you may also want to explore my other blog post Step-By-Step Guide to Get Started with Salesforce SOAP API using Java to learn how to get started with Salesforce SOAP API using Java or explore A 60 Minutes Step-By-Step DIY Guide to Salesforce REST API for Non-Developers to get started with REST API without going through the hassles of writing a Java program )
Even if you are not a developer, you should be able to follow the guide and have working java program at the end of it. Sounds interesting? Download the following presentation and let’s get started…
Introducing Mastering Salesforce APIs Training Course
Liked this post? We are now offering a complete self-paced, video-based training course on Mastering Salesforce APIs. The course comes with downloadable step-by-step PDF guides, unlimited access, free upgrades, community discussion area, free preview and more. For more details, please click here.
Here is the URL to get the code used in this guide
- Java program to connect to test connecting to Salesforce
- Java program to query, create, update & delete records in Salesforce
Not only this, you can go a step further and use other RESTful APIs that Salesforce provides to extract and manipulate data and metadata. For a list of different APIs along with a brief explanation on which API should be used when, please navigate to URL https://help.salesforce.com/HTViewHelpDoc?id=integrate_what_is_api.htm
References & Useful URLs
- Salesforce REST API Developer Guide – https://www.salesforce.com/us/developer/docs/api_rest/
- Setting Up Your Java Developer Environment – https://help.salesforce.com/help/pdfs/en/salesforce_developer_environment_tipsheet.pdf
Hi Satish/Asagarwal-
Did you get any solution to this. How you fixed it?
Hi Geeti, sorry but can you please clarify solution to which problem are you looking for?
Hi, I’m having the issue:
{
“error”: “invalid_grant”,
“error_description”: “authentication failure”
}
I’ve tried all the suggestions in the comments but nothing seems to be working for me.
Do you have any ideas on this?
Thank you
Hi Anderia, are you including the security token with your password? Please also take a look at the URL https://help.salesforce.com/articleView?id=remoteaccess_oauth_flow_errors.htm&type=0. More often than not, this error is thrown because we have missed some minor thing.
Hi asagarwal,
I am trying to deactivate a user but when i compile my code getting the following error:Exception in thread “main” java.lang.Error: Unresolved compilation problems:
The method getStatusLine() is undefined for the type HttpResponse
The method getEntity() is undefined for the type HttpResponse
The method getStatusLine() is undefined for the type HttpResponse
The method releaseConnection() is undefined for the type HttpPost
at salesforcerestapi.DeactivateUser.main(DeactivateUser.java:68)
Attaching my entire code:
package salesforcerestapi;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.json.JSONObject;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONTokener;
import org.json.JSONException;
public class DeactivateUser {
static final String USERNAME = “username@salesforce.com”;
static final String PASSWORD = “passwordSecurityToken”;
static final String LOGINURL = “https://login.salesforce.com”;
static final String GRANTSERVICE = “/services/oauth2/token?grant_type=password”;
static final String CLIENTID = “ConsumerKeyFromSalesfoceConnectedApps”;
static final String CLIENTSECRET = “ConsumerSecretFromSalesforceConnectedApps”;
private static String REST_ENDPOINT = “/services/data” ;
private static String API_VERSION = “/v32.0” ;
private static String baseUri;
private static Header oauthHeader;
private static Header prettyPrintHeader = new BasicHeader(“X-PrettyPrint”, “1”);
private static String leadId ;
private static String leadFirstName;
private static String leadLastName;
private static String leadCompany;
public static void main(String[] args) {
HttpClient httpclient = HttpClientBuilder.create().build();
// Assemble the login request URL
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
// Login requests must be POSTs
HttpPost httpPost = new HttpPost(loginURL);
HttpResponse response = null;
try {
// Execute the login POST request
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);
// Error is in EntityUtils.toString(response.getEntity())
return;
}
String getResult = null;
try {
getResult = EntityUtils.toString(response.getEntity());
} catch (IOException ioException) {
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 jsonException) {
jsonException.printStackTrace();
}
baseUri = loginInstanceUrl + REST_ENDPOINT + API_VERSION ;
oauthHeader = new BasicHeader(“Authorization”, “OAuth ” + loginAccessToken) ;
System.out.println(“oauthHeader1: ” + oauthHeader);
System.out.println(“\n” + 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);
// Run codes to query, isnert, update and delete records in Salesforce using REST API
queryLeads();
//createLeads();
updateLeads();
//deleteLeads();
// release connection
httpPost.releaseConnection();
}
private static void updateLeads() {
// TODO Auto-generated method stub
}
// Query Leads using REST HttpGet
public static void queryLeads() {
System.out.println(“\n_______________ Lead QUERY _______________”);
try {
//Set up the HTTP objects needed to make the request.
HttpClient httpClient = HttpClientBuilder.create().build();
String uri = baseUri + “/query?q=Select+Id+,+FirstName+,+LastName+,+Company+From+Lead+Limit+5”;
System.out.println(“Query URL: ” + uri);
HttpGet httpGet = new HttpGet(uri);
System.out.println(“oauthHeader2: ” + oauthHeader);
httpGet.addHeader(oauthHeader);
httpGet.addHeader(prettyPrintHeader);
// Make the request.
HttpResponse response = httpClient.execute(httpGet);
// Process the result
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
System.out.println(“JSON result of Query:\n” + json.toString(1));
JSONArray j = json.getJSONArray(“records”);
for (int i = 0; i < j.length(); i++){
leadId = json.getJSONArray("records").getJSONObject(i).getString("Id");
leadFirstName = json.getJSONArray("records").getJSONObject(i).getString("FirstName");
leadLastName = json.getJSONArray("records").getJSONObject(i).getString("LastName");
leadCompany = json.getJSONArray("records").getJSONObject(i).getString("Company");
System.out.println("Lead record is: " + i + ". " + leadId + " " + leadFirstName + " " + leadLastName + "(" + leadCompany + ")");
}
} catch (JSONException je) {
je.printStackTrace();
}
} else {
System.out.println("Query was unsuccessful. Status code returned is " + statusCode);
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
public static void updateLeads(Object Id) {
System.out.println("\n_______________ Lead UPDATE _______________");
//Notice, the id for the record to update is part of the URI, not part of the JSON
String uri = baseUri + "/sobjects/Lead/" + leadId;
try {
//Create the JSON object containing the updated lead last name
//and the id of the lead we are updating.
JSONObject lead = new JSONObject();
lead.put("LastName", "Lead –UPDATED");
System.out.println("JSON for update of lead record:\n" + lead.toString(1));
JSONObject lead1 = new JSONObject();
Id.IsActive = false;
lead.put("Id", "Lead1 –UPDATED");
System.out.println("JSON for update of leadId record:\n" + lead.toString(1));
//Set up the objects necessary to make the request.
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPatch httpPatch = new HttpPatch(uri);
httpPatch.addHeader(oauthHeader);
httpPatch.addHeader(prettyPrintHeader);
StringEntity body = new StringEntity(lead.toString(1));
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 == 204) {
System.out.println("Updated the lead successfully.");
} else {
System.out.println("Lead 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();
}
}
// Extend the Apache HttpPost method to implement an HttpPatch
private static class HttpPatch extends HttpPost {
public HttpPatch(String uri) {
super(uri);
}
public String getMethod() {
return "PATCH";
}
}
private static String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}
}
can you please help me with this issue.
Hi ASAGARWAL,
Can you please provide java REST API code to Deactivate and Reactivate users in Salesforce.
Thanks in Advance
Hi Asharani,
I don’t have the code readily available with me but what you need to do is to update the user record and set the value of the field ‘IsActive’ to true to make the user active and to false to deactivate the user. How to update records is covered in this blog post so your can refer to that specific section for exact steps on how to update records.
Thanks,
Ashish
You mean the
leadId = json.getJSONArray(“records”).getJSONObject(i).getString(“Id”);
Id.IsActive = false;
I am filtering on the basis of user id.
Yep, that should work.
I am getting the following error when i copy paste your code can u please suggest solution for this.
The method getStatusLine() is undefined for the type HttpResponse
The method getEntity() is undefined for the type HttpResponse
The method getStatusLine() is undefined for the type HttpResponse
The method releaseConnection() is undefined for the type HttpPost
Hi,
when i copy paste the code i am getting the following error:
Exception in thread “main” java.lang.Error: Unresolved compilation problems:
The method getStatusLine() is undefined for the type HttpResponse
The method getEntity() is undefined for the type HttpResponse
The method getStatusLine() is undefined for the type HttpResponse
The method releaseConnection() is undefined for the type HttpPost
Hi asagarwal,
I am trying to deactivate a user based on id when i complile my code i am getting the following error:
Exception in thread “main” java.lang.Error: Unresolved compilation problems:
The method getStatusLine() is undefined for the type HttpResponse
The method getEntity() is undefined for the type HttpResponse
The method getStatusLine() is undefined for the type HttpResponse
The method releaseConnection() is undefined for the type HttpPost
at salesforcerestapi.DeactivateUser.main(DeactivateUser.java:68)
Attaching the entire code:
package salesforcerestapi;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import org.json.JSONObject;
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.json.JSONArray;
import org.json.JSONTokener;
import org.json.JSONException;
public class DeactivateUser {
static final String USERNAME = “username@salesforce.com”;
static final String PASSWORD = “passwordSecurityToken”;
static final String LOGINURL = “https://login.salesforce.com”;
static final String GRANTSERVICE = “/services/oauth2/token?grant_type=password”;
static final String CLIENTID = “ConsumerKeyFromSalesfoceConnectedApps”;
static final String CLIENTSECRET = “ConsumerSecretFromSalesforceConnectedApps”;
private static String REST_ENDPOINT = “/services/data” ;
private static String API_VERSION = “/v32.0” ;
private static String baseUri;
private static Header oauthHeader;
private static Header prettyPrintHeader = new BasicHeader(“X-PrettyPrint”, “1”);
private static String leadId ;
private static String leadFirstName;
private static String leadLastName;
private static String leadCompany;
public static void main(String[] args) {
HttpClient httpclient = HttpClientBuilder.create().build();
// Assemble the login request URL
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
// Login requests must be POSTs
HttpPost httpPost = new HttpPost(loginURL);
HttpResponse response = null;
try {
// Execute the login POST request
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);
// Error is in EntityUtils.toString(response.getEntity())
return;
}
String getResult = null;
try {
getResult = EntityUtils.toString(response.getEntity());
} catch (IOException ioException) {
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 jsonException) {
jsonException.printStackTrace();
}
baseUri = loginInstanceUrl + REST_ENDPOINT + API_VERSION ;
oauthHeader = new BasicHeader(“Authorization”, “OAuth ” + loginAccessToken) ;
System.out.println(“oauthHeader1: ” + oauthHeader);
System.out.println(“\n” + 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);
// Run codes to query, isnert, update and delete records in Salesforce using REST API
queryLeads();
//createLeads();
updateLeads();
//deleteLeads();
// release connection
httpPost.releaseConnection();
}
private static void updateLeads() {
// TODO Auto-generated method stub
}
// Query Leads using REST HttpGet
public static void queryLeads() {
System.out.println(“\n_______________ Lead QUERY _______________”);
try {
//Set up the HTTP objects needed to make the request.
HttpClient httpClient = HttpClientBuilder.create().build();
String uri = baseUri + “/query?q=Select+Id+,+FirstName+,+LastName+,+Company+From+Lead+Limit+5”;
System.out.println(“Query URL: ” + uri);
HttpGet httpGet = new HttpGet(uri);
System.out.println(“oauthHeader2: ” + oauthHeader);
httpGet.addHeader(oauthHeader);
httpGet.addHeader(prettyPrintHeader);
// Make the request.
HttpResponse response = httpClient.execute(httpGet);
// Process the result
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
System.out.println(“JSON result of Query:\n” + json.toString(1));
JSONArray j = json.getJSONArray(“records”);
for (int i = 0; i < j.length(); i++){
leadId = json.getJSONArray("records").getJSONObject(i).getString("Id");
leadFirstName = json.getJSONArray("records").getJSONObject(i).getString("FirstName");
leadLastName = json.getJSONArray("records").getJSONObject(i).getString("LastName");
leadCompany = json.getJSONArray("records").getJSONObject(i).getString("Company");
System.out.println("Lead record is: " + i + ". " + leadId + " " + leadFirstName + " " + leadLastName + "(" + leadCompany + ")");
}
} catch (JSONException je) {
je.printStackTrace();
}
} else {
System.out.println("Query was unsuccessful. Status code returned is " + statusCode);
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
public static void updateLeads(Object Id) {
System.out.println("\n_______________ Lead UPDATE _______________");
//Notice, the id for the record to update is part of the URI, not part of the JSON
String uri = baseUri + "/sobjects/Lead/" + leadId;
try {
//Create the JSON object containing the updated lead last name
//and the id of the lead we are updating.
JSONObject lead = new JSONObject();
lead.put("LastName", "Lead –UPDATED");
System.out.println("JSON for update of lead record:\n" + lead.toString(1));
JSONObject lead1 = new JSONObject();
Id.IsActive = false;
lead.put("Id", "Lead1 –UPDATED");
System.out.println("JSON for update of leadId record:\n" + lead.toString(1));
//Set up the objects necessary to make the request.
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPatch httpPatch = new HttpPatch(uri);
httpPatch.addHeader(oauthHeader);
httpPatch.addHeader(prettyPrintHeader);
StringEntity body = new StringEntity(lead.toString(1));
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 == 204) {
System.out.println("Updated the lead successfully.");
} else {
System.out.println("Lead 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();
}
}
// Extend the Apache HttpPost method to implement an HttpPatch
private static class HttpPatch extends HttpPost {
public HttpPatch(String uri) {
super(uri);
}
public String getMethod() {
return "PATCH";
}
}
private static String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}}
Can u please help me with this issue
I get the following error in VS Code:
Main.java is a non-project file, only syntax errors are reported. Java(16) [1, 1]
Any ideas how to fix?
How to create only opportunity in salesforce?
Thank you so much Ashish! This is one of the few times that I was able to follow the detailed instruction and things just worked!
You have saved me several days of searching and trying out and failing and trying out again!
Thanks Asagarwal – outstanding example!
Thanks Ian!
thank you for this knowledge full tutorial.
please advise how to connect erb system to salesforce
i understood that we got the data inside the java console but what if i need to get data from erb to salesforce ?
I need help for sales force integration with java portal
Please, let me know, from where I will get Security Token to be used in Password?
Hi Pratik, The security token is sent to your email when you change your password. If you do not have the security token you can click on your image on the top right-hand side (in Lighting Experience) after logging on to Salesforce -> click settings -> navigate to ‘Reset My Security Token’ -> and then click on ‘Reset My Security Token’ button. Once done, you will receive it in your email. If you do not see this option, then there is ‘Login IP Ranges’ defined under your user’s profile. In that case, you do not need a security token at all. Just enter your password and you will be good to go. Hope this helps.
Hi Ashish and thanks for a great How To Article.
I was wondering if there is an exisiting Framework out there that implements all the Rest API calls to Salesforce using Java?
So for example, just like you provided the great examles of how to Query Leads or Create/Delete leads, has anyone implemented the rest of the API connectivity to Slaesfore using Java (or any other programming langugae for that matter) and created an implemetation for all other Salesfore Sobjects and the different API functionality that can be exeucted on them.
Have you heard about such a framework before?
Thanks,
Amit
Hi Amit, No, I am not aware of any such Framework. Though once you know the basics of how to call Salesforce REST API from a java program, it should be pretty easy to extrapolate that for other calls as well. You may want to refer to Salesforce REST API Developer’s guide that contains details of all the calls that Salesforce supports. It is available at URL https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/intro_what_is_rest_api.htm
Ashish, thank you so much for this detailed post. The screenshots on how to configure the Connect App with the dummy Callback URL was great. Also, showing that the overall PASSWORD is really a composite of user password + security token finally got things working for me. Thank you so much for sharing, Markus
Thanks for your feedback, Marcus. It is great to know that the post was useful to you.
Hi Ashish,
From where we can get Security Token That needs to be appended to Password. Can you please help.
Hi Veerendra, The security token is sent to your email when you change your password. If you do not have the security token you can click on your image on the top right-hand side (in Lighting Experience) after logging on to Salesforce -> click settings -> navigate to ‘Reset My Security Token’ -> and then click on ‘Reset My Security Token’ button. Once done, you will receive it in your email. If you do not see this option, then there is ‘Login IP Ranges’ defined under your user’s profile. In that case, you do not need a security token at all. Just enter your password and you will be good to go. Hope this helps.
works fine, thank you..
but i really dont understand , what these 5 leads are coming from?
why d0nt i see leeds from my console app?
Not sure if I understood your question, Marc. By 5 leads if you are referring to the SOQL Query, please note that every developer org in Salesforce has some sample data and these 5 leads are coming from that sample data. If you do not have these sample records in your Salesforce Org, you won’t see the data.
ah, that’s an info a wasnt aware of before. however, i can even see more that those 5 ..
maybe you can also point me exactly to the place i can find them.. within my new console application i cannot see a single one of them
btw: thanks for your fast answer 🙂
still cannot find those demo leads. there are exactly 24. I created 2 and those 2 are within the listed 24, but the other 22 i cannot find anywhere..
weird.
Great tutorial on REST API…..! One of the most thorough and best I have seen. Kudos…! I have done Java Development and Salesforce integration as well, but it has been some time, so this was exactly what I needed to get back in the game again. Thanks again
-Niels
Thanks for you feedback Neil. Glad that you found it helpful.
I tried this code to access the https://test.salesforce.com but getting SSL handshake error. Will this code works both http and https?
Salesforce APIs only support https. It won’t work with http. You also need to use a certificate that is signed by a Certification Authority (CA) that Salesforce trusts. Please navigate to URL https://help.salesforce.com/articleView?id=000007225&type=1 for more details on how to find out the CA that Salesforce trusts
Thank you for the tutorial Asagarwal.
For those who would like to use special characters on the password (like me) Just encode the url
import java.net.URLEncoder;
String loginURLencoded = LOGINURL + GRANTSERVICE +”&client_id=”+URLEncoder.encode(CLIENTID, “UTF-8″)+”&client_secret=” + CLIENTSECRET +”&username=” + URLEncoder.encode(USERNAME, “UTF-8″) +”&password=” +URLEncoder.encode(PASSWORD, “UTF-8”);
Thanks for the tip Magnot!
This is very useful post thanks for sharing it. Do you have a way where we can add custom fields as well using these REST APIs? Any sample code will be very helpful.
It was really helpful. Appreciate your efforts the way you have provided step-by-step instructions. Thanks for a wonderful post.
I tried all the solutions but still getting same error “Error authenticating to Force.com: 400”. Please help me resolve the same
i am getting handshake error . can someone please help.
Hi Ashish,
I am getting this issue while querying SF Object, plz give solution for this…
http3.OkHttpClient – <– 400 Bad Request https:///services/data/v41.0/query?q=Select%2BId%2B,%2BName%2B,%2BEmail%2B,%2BFrom%2BContact%2BWhere&email=suma.reddy@test.com (6746ms)
13:05:54.931 [http-nio-8080-exec-1] INFO okhttp3.OkHttpClient – [{“message”:”\nSelect+Id+,+Name+,+Email+,+From+Contact+Where\n ^\nERROR at Row:1:Column:6\nunexpected token: ‘+'”,”errorCode”:”MALFORMED_QUERY”}]
13:05:54.934 [http-nio-8080-exec-1] INFO okhttp3.OkHttpClient – <– END HTTP (149-byte body)
This was really helpful – thanks for documenting it.
Thanks for your feedback Bhavana
Hi Ashish,
Please help me how to do the below query in SF rest api–SELECT name, id, email from Contact where email=’suma@test.com’
can someone please check the code and mistake I am doing? It will be really helpful
org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:187)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
at salesoforce_automation.Sfdc.main(Sfdc.java:43)
Caused by: org.apache.http.ProtocolException: Target host is not specified
at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
… 4 more
Exception in thread “main” java.lang.NullPointerException
at salesoforce_automation.Sfdc.main(Sfdc.java:51)
Hi Ashish,
How can I deploy my custom java application I created using your article in Salesforce. I want that my code/app is scheduled in/out of Salesforce.
Comments from other members are also welcome 🙂
Naveed
Above code supports single record add, update and delete.
is there a way to upload bulk records using API ( not the bulk API, the excel way) using similar code like above
Hi,
I also have the problems with “400”. My solution :
1) In example code change “&” in “&” (not sure if this was the problem)
2) change “IP Restrictions” to “Relax IP restrictions”. This was definitely the problem.
Regards,
Matic
Thank you this really helped solve my issue!
Connect to login.salesforce.com:443 [login.salesforce.com/136.147.40.172, login.salesforce.com/136.147.56.44, login.salesforce.com/136.147.56.172, login.salesforce.com/136.147.43.172] failed: Connection refused: connectException in thread “main”
Really usefull giude for successfully implementing salesforce…
Hi Ashish,
I am using the code shared by you and also tried fixing 400 error issues. I follow all the methods mentioned by you still problem is not yet resolved. I removed amp; from the url as well and also give all the permissions.
When i tried printing url i got this message along with error.
https://ap4.salesforce.com/services/oauth2/token?grant_type=password&client_id=4MVG9YDQS5WtC11qoumKOZQbWgsdkg9iO1vpIy0nhGHcanHacevSgJrOuDXxjnX6Xmv22gxg1nS2898Z1taWe&client_secret=4380894129824044251&username=sumit17032018@gmail.com&password=Admin#12345VUVv54QzKdoxpXxyI84kFGhYt
Can you pls check what’s the error in the code.
Sharing complete code with you . Thanks in advance
package salesforce_rest;
import java.io.IOException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.JSONException;
public class Main {
static final String USERNAME = “sumit1703201b@gmail.com”;
static final String PASSWORD = “Admin#12345VUVv54QzKdoxpXxyI84kFGhYt”;
static final String LOGINURL = “https://ap4.salesforce.com”;
static final String GRANTSERVICE = “/services/oauth2/token?grant_type=password”;
static final String CLIENTID = “4MVG9YDQS5WtC11qoumKOZQbWgsdkg9iO1vpIy0nhGHcanHacevSgJrOuDXxjnX6Xmv22gxg1nS2898Z1taWe”;
static final String CLIENTSECRET = “4380894129824044251”;
public static void main(String[] args)
{
HttpClient httpclient = HttpClientBuilder.create().build();
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
System.out.print(loginURL);
HttpPost httpPost = new HttpPost(loginURL);
HttpResponse response = null;
try {
// Execute the login POST request
response = httpclient.execute(httpPost);
}
catch (ClientProtocolException cpException)
{
cpException.printStackTrace();
}
catch (IOException ioException)
{
ioException.printStackTrace();
}
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
{
System.out.println(“Error authenticating to Force.com: “+statusCode);
// Error is in EntityUtils.toString(response.getEntity())
return;
}
String getResult = null;
try
{
getResult = EntityUtils.toString(response.getEntity());
} catch (IOException ioException)
{
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 jsonException)
{
jsonException.printStackTrace();
}
System.out.println(response.getStatusLine());
System.out.println(“Successful login”);
System.out.println(“instance URL: “+loginInstanceUrl);
System.out.println(“access token/session ID: “+loginAccessToken);
// release connection
httpPost.releaseConnection();
}
}
CAUTION , copy/paste will change & into & resulting in 400.
I had the same problem which I resolved setting the connected app “IP Restrictions” to “Relax IP restrictions”
Dear Asagarwal,
I am behind the firewall and followed all the steps and solutions which were suggested. Still getting the 400 error.
Status Code: 400
Error authenticating to Force.com: 400
Response Text: {“error”:”unknown_error”,”error_description”:”retry your request”}
Can you please help? Thanks!
Precious post and suggestions to make it work. I think most of the people are missing these three tips you mentioned earlier. I faced the same 400 issue and resolved it by your suggestions.
1. Most of the Developer Org are not using IP Restrictions. So they need to remove the “Security Token.” from their passwords.
2. Do not use the & as suggested earlier.
3. Adding profile to the Connected App.
I was having the 400 issue, removed “Security Token” and can not log in. Thanks for your post.
Thanks Steven
Agree – Great Post. If you have a custom Salesforce domain you need to use that domain or you will also see the 400 error.
Next step – turn this example into a Spring Boot application…anyone done this already? Happy to share once I’m done 😉
Agree great post…a couple of minor Java compile issues related to cut and paste I believe.
If you have a Salesforce custom domain you need to use that domain not the login.salesforce.com domain. I was getting the 400 without this change.
Next step is to turn this into a Spring Boot application…anyone else already tackled that? Happy to share once I’m done…
Error authenticating to Force.com: 400
seems to be the common theme… 🙁
Hi ASAGARWAL,
Thanks very much for your post. It helped very much.
My URL string is working using REST client and getting the Access token. But the same URL when invoked using the HttpPost is not working.
As you mentioned, I do not have “&” or “amp;” in the URL.
https://test.salesforce.com/services/oauth2/token?grant_type=password&client_id=CLIENT_ID_VALUE&client_secret=CLIENT_SECRET_VALUE&username=USER_NAME_VALUE&password=PASSWORD_VALUE
Error authenticating to Force.com: 400
Hi Sir,
I followed every step that you have mentioned but I am getting Error “Error authenticating to Force.com: 400”.
Below is my Code:
public class Main {
static final String USERNAME = “tanujsfdcfsp@gmail.com”;
static final String PASSWORD = “WeLcome!@#1SIGPQ0TvD2QiPsCGBCtBM3fll”;
static final String LOGINURL = “https://login.salesforce.com”;
static final String GRANTSERVICE = “/services/oauth2/token?grant_type=password”;
static final String CLIENTID = “3MVG9ZL0ppGP5UrDyp4ee2h.UVjTtq73y8czd0hycjApzl6WCzSOarGVnje4NVSqDbRvM0WHHYxVJfjY.YxpE”;
static final String CLIENTSECRET = “4000568907354822642”;
public static void main(String[] args) {
DefaultHttpClient httpclient = new DefaultHttpClient();
// Assemble the login request URL
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
// Login requests must be POSTs
HttpPost httpPost = new HttpPost(loginURL);
/// HttpGet httpGet = new HttpGet(loginURL);
HttpResponse response = null;
try {
// Execute the login POST request
response = httpclient.execute(httpPost);
} catch (ClientProtocolException cpException) {
System.out.println(“Exception: “+cpException);
// Handle protocol exception
} catch (IOException ioException) {
// Handle system IO exception
}
// 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);
// Error is in EntityUtils.toString(response.getEntity())
return;
}
String getResult = null;
try {
getResult = EntityUtils.toString(response.getEntity());
} catch (IOException ioException) {
// Handle system IO exception
}
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 jsonException) {
// Handle JSON exception
}
System.out.println(response.getStatusLine());
System.out.println(“Successful login”);
System.out.println(” instance URL: “+loginInstanceUrl);
System.out.println(” access token/session ID: “+loginAccessToken);
// release connection
httpPost.releaseConnection();
}
This is a great post with step by step instructions !!
You are really Awesome !!!! I was stuck with .NET code from couple of hours finally used your code and it worked like magic!!
Appreciate your great works !!
Thanks Vaibhav. Glad that it was helpful to you.
400 issue is fixed after removing the semicolons like JeevanK Suggested. Thank you JeevanK!
Asagarwal, I’m so gratefull that you took the time to write this blog. Thank Thank you.
Thanks Ernesto !
Excellent post. It works fine with 1.8 JDK . But with 1.7 getting org.apache.http.client.ClientProtocolException any suggestion will be helpful
My code can run on JDK1.8, When run on the JDK1.6, it can’t run. and throw the error as below!
Error authenticating to Force.com: 400
Hi ASAGARWAL,
Thanks for this posting. It worked well for me. I have version issue when I change the json jar to latest version (2016212) Any suggestion how I can make this code work with new version?
Wonderful post.I was searching for a simple Java -SF integration program..I too got 400 issue.But after correcting the URL, I could connect.Thanking you once again!!
You are welcome. Glad it helped.
Excellent post. Really helpful and self explanatory. Thank you asagarwal !!
Thanks Subhojit
400 issue is fixed after removing the semicolon thanks JeevanK
thanks a lot….You are godsend for noobs like us…Really appreciate your effort and willingness to share your knowledge with the world.
Thanks Again.
Hi
Do you know how I can copy paste this code?
Hi Asagarwal,
I have done java to developer edition integaration.it’s working fine. but i have same things done in sandbox but i am getting erroor code 400.
Note:I have using is Below “LOGINURL = “https://test.salesforce.com”;”
I am getting below error –
baseUri: https://ap2.salesforce.com/services/data/v32.0
java.lang.Error: Unresolved compilation problems:
lt cannot be resolved to a variable
Syntax error on token “;”, , expected
at salesforce_rest.Main.queryLeads(Main.java:140)
Code Snippet-
for (int i = 0; i < ;j.length(); i++){
leadId = json.getJSONArray(“records”).getJSONObject(i).getString(“Id”);
leadFirstName = json.getJSONArray(“records”).getJSONObject(i).getString(“FirstName”);
leadLastName = json.getJSONArray(“records”).getJSONObject(i).getString(“LastName”);
leadCompany = json.getJSONArray(“records”).getJSONObject(i).getString(“Company”);
System.out.println(“Lead record is: ” + i + “. ” + leadId + ” ” + leadFirstName + ” ” + leadLastName + “(” + leadCompany + “)”);
}
Can anyone suggest what is missing here.
I was trying to use same Java Code to Connect, Query, Insert, Update & Delete posted by Ashish but ended with below error-
java.lang.Error: Unresolved compilation problems:
lt cannot be resolved to a variable
Syntax error on token “;”, , expected
Code Snippet-
for (int i = 0; i < ;j.length(); i++){
leadId = json.getJSONArray(“records”).getJSONObject(i).getString(“Id”);
leadFirstName = json.getJSONArray(“records”).getJSONObject(i).getString(“FirstName”);
leadLastName = json.getJSONArray(“records”).getJSONObject(i).getString(“LastName”);
leadCompany = json.getJSONArray(“records”).getJSONObject(i).getString(“Company”);
System.out.println(“Lead record is: ” + i + “. ” + leadId + ” ” + leadFirstName + ” ” + leadLastName + “(” + leadCompany + “)”);
}
Can anyone suggest what is missing here.
hi even i am getting the same error like u ..
I was trying to use same Java Code to Connect, Query, Insert, Update & Delete posted by Ashish but ended with below error-
java.lang.Error: Unresolved compilation problems:
lt cannot be resolved to a variable
Syntax error on token “;”, , expected
Code Snippet-
for (int i = 0; i < ;j.length(); i++){
leadId = json.getJSONArray(“records”).getJSONObject(i).getString(“Id”);
leadFirstName = json.getJSONArray(“records”).getJSONObject(i).getString(“FirstName”);
leadLastName = json.getJSONArray(“records”).getJSONObject(i).getString(“LastName”);
leadCompany = json.getJSONArray(“records”).getJSONObject(i).getString(“Company”);
System.out.println(“Lead record is: ” + i + “. ” + leadId + ” ” + leadFirstName + ” ” + leadLastName + “(” + leadCompany + “)”);
}
If anyone resolved this issue pls let me know
Hi,
I am getting below error. Please help.
org.apache.http.conn.HttpHostConnectException: Connect to login.salesforce.com:443 [login.salesforce.com/136.147.56.44, login.salesforce.com/136.147.57.44, login.salesforce.com/136.147.58.44, login.salesforce.com/136.147.58.172] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:158)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at sfdc.Main.main(Main.java:45)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:337)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
… 11 more
Exception in thread “main” java.lang.NullPointerException
at sfdc.Main.main(Main.java:55)
Hi,
I am getting below error while running the code. Please help .
org.apache.http.conn.HttpHostConnectException: Connect to login.salesforce.com:443 [login.salesforce.com/136.147.56.44, login.salesforce.com/136.147.57.44, login.salesforce.com/136.147.58.44, login.salesforce.com/136.147.58.172] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:158)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at sfdc.Main.main(Main.java:45)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:337)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
… 11 more
Exception in thread “main” java.lang.NullPointerException
at sfdc.Main.main(Main.java:55)
Hi Agarwal,
Need small help.
How to mark unread record to recently viewed record with REST API or SOAP API?
I Tried using the similar approach which Jeevank tried, but got the 400 bad request error.
here is the login URL which was used
https://login.salesforce.com/services/oauth2/token?grant_type=password&client_id=&client_secret=&username=&password=
chech this post
http://www.calvinfroedge.com/salesforce-how-to-generate-api-credentials/
Hello Ashish,
I am following exact what you mentioned in the blog for Read (HttpGet) and Create(HttpPOST). I got success in read but not in Create. I am getting 400 error. can you please guide me here, Following is my code :
//Set up the HTTP objects needed to make the request.
HttpClient httpClient = HttpClientBuilder.create().build();
String uri = baseUri;
HttpPost httpPost = new HttpPost(uri);
System.out.println(“Query URL: ” + uri);
System.out.println(“oauthHeader2: ” + oauthHeader);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
JSONObject lead = new JSONObject();
JSONObject subJson = new JSONObject();
subJson.put(“ApplicationStatus”,”New”);
subJson.put(“Candidate”,”a1D15000003XxLQEA0″);
subJson.put(“Distance”,”25″);
subJson.put(“DocuSignEnvelopeId”,”ABCD”);
subJson.put(“DocuSignStatus”,”Delivered”);
subJson.put(“JobOpening”,”a2I15000000OXIHEA4″);
subJson.put(“LastDocuSignStatus”,”2015-02-02T11:00:00.000Z”);
subJson.put(“Score”,”60″);
lead.put(“records”, subJson);
System.out.println(“JSON for lead record to be inserted:\n” + lead.toString(1));
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType(“application/json”);
httpPost.setEntity(body);
// Make the request.
HttpResponse response = httpClient.execute(httpPost);
System.out.println(“\n_______________ STEP 2_______________”);
// Process the result
int statusCode = response.getStatusLine().getStatusCode();
Hello Ashish,
Still have ‘Error authenticating to Force.com: 400’ . even after following all.
Thanks,
Mouli K
For anyone looking at this tutorial and having the 400 authentication error, here is what I had to do:
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
In other words, it did not work if I had a semicolon after each of the ampersands. Trivial, yes..but it cost me several several hours and hope that you don’t have to go through the same thing!
As mentioned in comment by srinivas, you need to remove the amp; from the login url:
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
Also, if your email address has plus symbol in it (e.g. myname+salesforce-signup@gmail.com) then you need to replace the + with %2b (e.g. myname%2bsalesforce-signup@gmail.com)
Thank you
Hi Ashish,
Could you please provide step by step guide for getting the access token through JWT approach. I followed the below link but got struck badly. Kindly help.
Hi Santosh, I do not have the step-by-step guide now but this will make an interesting & useful post. I will add it to my to-do list of blog posts.
Hi Ashish,
I am able to get the access token and instance url with “User name and Password” approach . Is it possible for you provide the step by step guide to get the access token through JWT approach? I am badly struck in JWT approach. Followed the below link but no luck. I guess there is some issue in Certificate part.
https://help.salesforce.com/HTViewHelpDoc?id=remoteaccess_oauth_jwt_flow.htm
To all getting error in connecting to Salesforce through REST API, here are a couple of things you need to check
1. The profile of the user you are connecting to has ‘API Enabled’ permission (Setup -> Users -> Profile -> Profile Name -> System Permissions)
2. You have given the correct ‘OAuth Scope’ when creating Connected Apps. If in doubt, select ‘Full Access (full)’ OAuth scope and try (Setup -> Create -> Apps -> Connected App Name)
3. If the ‘Permitted Users’ under ‘OAuth Policies’ is defined as ‘Admin approved users are pre-authorized’, you have added the profile of the user with which you are trying to connect to the ‘Profiles’ under that ‘Connected App’ (Setup -> Create -> Apps -> Connected App Name -> Manage -> Profiles)
4. ‘IP Relaxation’ is set to ‘Relax IP restrictions for the Connect App (Setup -> Create -> Apps -> Connected App Name -> Manage)
5. If you have NOT specified Login IP Ranges under Setup -> Manage Users -> Profiles -> Profile Name -> Login IP Ranges, then you are appending security token to your password when connecting through REST API
6. You password does not contain characters like ‘&’
Cheers,
Ashish
Thanks Ashish for such nice explanation. Initially got the 404 err but was resolved with your inputs. Its really very good for beginners and was very helpful to me as I am new to Salesforce.
Thanks Sangeeta, Glad to know hat it was helpful
i’m also facing same issue when connecting via REST API using Java.
Error authenticating to Force.com:400
{“error”:”invalid_grant”,”error_description”:”authentication failure”}
I’m stuck here,please help me on this.
who suffering with Error authenticating to Force.com: 400
remove all “amp;” from
String loginURL = LOGINURL +
GRANTSERVICE +
“&client_id=” + CLIENTID +
“&client_secret=” + CLIENTSECRET +
“&username=” + USERNAME +
“&password=” + PASSWORD;
it worked for me….
getting Error authenticating to Force.com: 400
Thanks for the great article Ashish
Thanks Raghav !
Great blog Ashish.
Really impressed!
The above code is working fine in dev org.
when I try the same with production credentials it shows error 400.
Thank You,
Arshad.
Hello Sir
I am new In salesforce. when i use this code and call salesforce rest service it getting me status code 200 after successfully login in org but when calling service after login then my service is not executed and giving same status code 200 instad of 201 for successfull POST request .
please help
Hello. For anyone with the 400 error trying to login. you need to relax the IP restrictions of the ORG.
Please check this link:
http://www.calvinfroedge.com/salesforce-how-to-generate-api-credentials/
Error authenticating to Force.com: 400 is either because of
1. Not granting all authentication scopes
or
2. Using # or any other url related characters
Hi Ashish,
I’m also getting the “Error authenticating to Force.com: 400” error message.
Hi Ashish,
This was extremely useful! I have been trying to learn how to do it for hours and hours without any positive result.
Thanks to you now I have an starting point.
Just tell you THANK YOU VERY MUCH!
Hi Ashish,
I am getting “Error authenticating to Force.com: 400”.
Hi,
I’m getting “Error authenticating to Force.com: 400” same steps I followed.
Excellent article, thank you very much!
Hi Ashish,
This was extremely useful! I was getting frustrated with the salesforce’s official REST API documentation as it doesn’t provide good code samples. This was easy to follow and very clear! My only recommendation would be that you could mention in the blog post that this example uses the “Username-Password OAuth Authentication Flow”, since there are different flows and it wasn’t very sure which one this was using, other than great, excellent job and thank you very very much. I look forward to reading more posts from you!
That makes sense. I’ll mention that explicitly. Thanks for your feedback Pablo.
just replace
Srushti,
here is the solution or proxy settings
replace HttpClient httpclient = HttpClientBuilder.create().setProxy(proxy).build();
with
int port=443;
HttpHost proxy = new HttpHost(“proxyhostname”,port );
HttpClient httpclient = HttpClientBuilder.create().setProxy(proxy).build();
simply superb!!..
I tried this one ,its working for me .thank you so much keep posting…!!!!
Words cannot express how extraordinarily helpful this was. I shall come to your house and sing “Wind Beneath My Wings” outside of your bedroom window! Or not if that seems too creepy.
Getting the below exception
Exception in thread “main” java.lang.NoSuchFieldError: INSTANCE
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:52)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:56)
at org.apache.http.impl.io.DefaultHttpRequestWriterFactory.(DefaultHttpRequestWriterFactory.java:46)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:69)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:81)
at org.apache.http.impl.conn.ManagedHttpClientConnectionFactory.(ManagedHttpClientConnectionFactory.java:56)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager$InternalConnectionFactory.(PoolingHttpClientConnectionManager.java:487)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:147)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:136)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.(PoolingHttpClientConnectionManager.java:112)
at org.apache.http.impl.client.HttpClientBuilder.build(HttpClientBuilder.java:459)
at salesforcewithrest.Main.main(Main.java:23)
Hi i am getting the same problem.plz tell me how to solve this
Error: java.net.UnknownHostException: login.salesforce.com at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source) at java.net.InetAddress.getAddressFromNameService(Unknown Source) at java.net.InetAddress.getAllByName0(Unknown Source) at java.net.InetAddress.getAllByName(Unknown Source) at java.net.InetAddress.getAllByName(Unknown Source) at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:111) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) at salesforce_rest.Main.main(Main.java:44) Exception in thread “main” java.lang.NullPointerException at salesforce_rest.Main.main(Main.java:53)
I am behind company proxy settings.I entered proxy details in pprferences->general->network connection in eclipse.Still not working… How to insert proxy settings in java code .. Please help..I am stuck for 3 days.Thanks in advance..
Excellent guide!!!
I have a question. In the guide it mentions that the Main.java code was on your blog somewhere. Can you point me to it?
Thanks Tad, The java code is just below the presentation slide on the blog. Click on the text “Java Code to Connect, Query, Insert, Update & Delete to Salesforce using REST API” and it will expand the code.
Many Thanks for the post on REST API.