How to download a file from Salesforce using Java Rest API

Reading Time: 2 minutes

Downloading a file from Salesforce using Java is not as difficult as it may seem. With the right tools and knowledge, you can quickly and easily download any type of file from Salesforce via a Rest API. To get started, you’ll need a few software tools and a few lines of code.

Let say we want to download a file stored in Salesforce. Have in mind we said a File and not an Attachment (the old way to deal with files in Salesforce), so we’ll have to deal with ContentDocument, ContentVersion, ContentDocumentLink, etc.

Agenda:

  • Salesforce security token
  • Partner API
  • Salesforce Rest API
  • Store a file

Implementation

We are going to use force-partner-api dependency to get a session id after login

If we use Maven, our pom.xml will have this dependency

   

<dependency>
    <groupId>com.force.api</groupId>
     <artifactId>force-partner-api</artifactId>
     <version>51.0.0</version>
</dependency>


Let’s have some constants to keep our params in one place.

      
    private static final Logger LOG = Logger.getLogger(Main.class.getName());
    private static final String USERNAME = "********";
    private static final String ACCESS_TOKEN = "********";
    private static final String PASSWORD = "********"+ACCESS_TOKEN;
    private static final String INSTANCE_URL = "https://********-dev-ed.my.salesforce.com";
    private static final String API_VERSION = "51.0";
    private static final String SALESFORCE_FILE_ID = "0684W00000AzWoiQAF"; // ContentVersion id
    private static final String LOCAL_FILE_FULL_NAME = ""/tmp/sf-java.png"";



Important: the ACCESS_TOKEN constant represents the Salesforce security token you get from Settings -> Reset My Security Token

When you access Salesforce from an IP address that isn’t trusted for your company, and you use a desktop client or the API, you need a security token to log in. What’s a security token? It’s a case-sensitive alphanumeric code that’s tied to your password. Whenever your password is reset, your security token is also reset.

After you reset your token, you can’t use your old token in API applications and desktop clients.


The method to get the file (download and save it in our local disk)

      
private static void getFile(String sessionId) throws Exception {
        String urlString = INSTANCE_URL+"/services/data/v"+API_VERSION+"/sobjects/ContentVersion/"+SALESFORCE_FILE_ID+"/VersionData";
        LOG.info(urlString);
        URL url = new URL(urlString);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Content-Type", "application/octet-stream");
        con.setRequestProperty("Authorization", "OAuth "+sessionId);
        LOG.info("Status "+con.getResponseCode());
        LOG.info("Status message "+con.getResponseMessage());
 
       // store the file in our disk
       Files.copy(con.getInputStream(), Paths.get(LOCAL_FILE_FULL_NAME) , StandardCopyOption.REPLACE_EXISTING);
    }

Imports you will need

      
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.logging.Logger;

import com.sforce.soap.partner.Connector;
import com.sforce.soap.partner.GetUserInfoResult;
import com.sforce.soap.partner.PartnerConnection;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;
import java.util.logging.Level;


The method to get our session id

      
private static PartnerConnection getConnection() throws ConnectionException {
        ConnectorConfig enterpriseConfig = new ConnectorConfig();
        enterpriseConfig.setUsername(USERNAME);
        enterpriseConfig.setPassword(PASSWORD);
        enterpriseConfig.setServiceEndpoint(INSTANCE_URL + "/services/Soap/u/" + API_VERSION);
        enterpriseConfig.setAuthEndpoint(INSTANCE_URL + "/services/Soap/u/" + API_VERSION);

        return Connector.newConnection(enterpriseConfig);
    }

The main method to call our method from above

      
public static void main(String[] args) {
        try {
            LOG.info("Start");
            PartnerConnection conn = getConnection();
            GetUserInfoResult userInfo = conn.getUserInfo();
            LOG.info(userInfo.getOrganizationName());
            LOG.info(conn.getConfig().getSessionId());
            getFile(conn.getConfig().getSessionId());
            LOG.info("End");
        }catch (Exception e){
            LOG.log(Level.SEVERE, e.getMessage());
            e.printStackTrace();
        }
    }

Photo by JF Martin on Unsplash

, ,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: