Step-By-Step Guide to Get Started with Salesforce REST API using Java

Step-By-Step Guide to Get Started with Salesforce REST API using Java

(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…

Not an “All Access” Pass Member Yet?

Get Download Access to this & 150+ More Step-by-Step Guides with “All Access” Pass. A simple and single plan to access our entire library of courses, guides, workshops & masterclasses on Salesforce.

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

  1. Java program to connect to test connecting to Salesforce 
  2. 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

  1. Salesforce REST API Developer Guide – https://www.salesforce.com/us/developer/docs/api_rest/
  2. Setting Up Your Java Developer Environment – https://help.salesforce.com/help/pdfs/en/salesforce_developer_environment_tipsheet.pdf

125 thoughts on “Step-By-Step Guide to Get Started with Salesforce REST API using Java”

      1. 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

  1. 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.

  2. Hi ASAGARWAL,
    Can you please provide java REST API code to Deactivate and Reactivate users in Salesforce.

    Thanks in Advance

    1. 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

      1. You mean the
        leadId = json.getJSONArray(“records”).getJSONObject(i).getString(“Id”);
        Id.IsActive = false;
        I am filtering on the basis of user id.

          1. 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

          2. 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

      2. 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

  3. 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?

  4. 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!

  5. 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 ?

    1. 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.

  6. 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

    1. 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

  7. 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

      1. Hi Ashish,

        From where we can get Security Token That needs to be appended to Password. Can you please help.

        1. 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.

  8. 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?

    1. 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.

      1. 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 🙂

      2. 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.

  9. 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

  10. 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”);

  11. 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.

  12. It was really helpful. Appreciate your efforts the way you have provided step-by-step instructions. Thanks for a wonderful post.

  13. I tried all the solutions but still getting same error “Error authenticating to Force.com: 400”. Please help me resolve the same

  14. 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)

      1. 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’

  15. 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)

  16. 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

  17. 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

  18. 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

  19. 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”

  20. 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();
    }

    }

  21. 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!

  22. Prolay Chaudhury

    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 &amp as suggested earlier.

    3. Adding profile to the Connected App.

  23. 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 😉

  24. 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…

  25. 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();
    }

  26. Vaibhav kaushik

    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 !!

  27. 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.

  28. Excellent post. It works fine with 1.8 JDK . But with 1.7 getting org.apache.http.client.ClientProtocolException any suggestion will be helpful

  29. 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

  30. 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?

  31. 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!!

  32. 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.

  33. 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”;”

  34. 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 &lt ;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.

  35. 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 &lt ;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.

    1. 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 &lt ;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

  36. 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)

  37. 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)

  38. Hi Agarwal,

    Need small help.
    How to mark unread record to recently viewed record with REST API or SOAP API?

  39. Piyush gautam

    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();

  40. 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!

  41. 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)

  42. Santosh Kulal

    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.

    1. 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.

  43. 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

    1. 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.

  44. 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.

  45. 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….

  46. 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.

  47. 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

  48. 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

  49. 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!

  50. 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!

  51. 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();

  52. 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.

  53. 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)

  54. 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..

  55. 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?

    1. 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.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
Introducing All Access Pass