Sample code to upload a file to chatter feed using REST API

January 06, 2014

Step 1: Download required files

  • Download the following files from internet
    • org.apache.commons.httpclient.jar
  • From the files, I have added following JARS to my project in eclipse.

Screenshot from Ecclipse
Step 2: Get Access Token Through Chrome

  • Login to your Salesforce instance and navigate to Setup -> Create -> Apps. 
  • Create a custom app and fill Client ID and CallBack URL (ex: in the following URL. Encode the CallBack URL before passing it as a parameter. 

  • Paste this URL in chrome
    • In Developer Tool -> Network select "preserve log upon navigation"
    • Load the page. We see below page.

    • The page will take us to RemoteAccessAuthorizationPage.apexp which inturn will lead us to _ui/identity/oauth/ui/AuthorizationPage
    • Finally the page will take you to CallBack URL providing it with Access Id. Get Access Id from CallBack URL.

  • And fetch the URL fragment to get the access token. We can use this in the program. 

Step 3: Code to post content to Chatter

I have started out of samples posted at
  • In this step we will create post in Account feed  with a file attachment and mention a person (@mention) in the body of the post.
  • The following example posts a comment to a feed and uploads a binary attachment

POST /services/data/v28.0/chatter/feed-items/0D5x00000000RryCAE/comments HTTP/1.1
    Authorization: OAuth 00DD0000000Jhd2!AQIAQC.lh4qTQcBhOPm4TZom5IaOOZLVPVK4wI_rPYJvmE8r2VW8XA.
        Accept: application/json
          User-Agent: Jakarta Commons-HttpClient/3.0.1
              Introducing Chatter REST API Using Chatter API Inputs
                Host: instance_name
                  Content-Length: 978
                    Content-Type: multipart/form-data; boundary=F9jBDELnfBLAVmLNbnLIYibT5Icp0h3VJ7mkI
                        Content-Disposition: form-data; name="json"
                          Content-Type: application/json; charset=UTF-8
                            { "body":
                                "messageSegments" : [
                                    "type" : "Text",
                                      "text" : "Here's another file for review."

                                        "type": "mention",
                                        "id" : "005D0000001GpHp"
                                        }, {
                                          "type" : "Hashtag",
                                            "tag" : "important"
                                              }, {
                                                "type" : "Text",
                                                  "text" : "Again, please review this as soon as possible."
                                                            "attachmentType" : "NewFile",
                                                              "description": "Quarterly review 2012 Q2",
                                                                "title" : "2012_q2"
                                                                        Content-Disposition: form-data; name="feedItemFileUpload"; filename="foo"
                                                                          Content-Type: application/octet-stream; charset=ISO-8859-1
                                                                            This is the content of the file.

                                                                              • The real trouble I faced is to prepare the request in Java.
                                                                                • First I created a POST method and created multi-part request entity.
                                                                                • To the multi-part request we have to pass two parts
                                                                                  • File Part - Binary data of the file (highlighted in aqua)
                                                                                  • Json Part - Contains body of the post and attachment details (highlighted in yellow)
                                                                                • HashMaps were used to represent JSON data. Once the data is prepared it is passed on to JSON part (StringPart) as string. Pay attention to content type, part name and chart set. 
                                                                                • A file part is created by accessing a PDF file from local drive
                                                                                • Both these parts are passed on to multi-part request object which is inturn used to fire a POST method
                                                                              The trick here is to understand the structure of the request structure and try to replicate the same in your program. 
                                                                              •  package com.jda.sf.chatter;  
                                                                                 import java.util.HashMap;  
                                                                                 import java.util.LinkedList;  
                                                                                 import java.util.List;  
                                                                                 import java.util.Map;  
                                                                                 import java.util.ArrayList;  
                                                                                 import org.apache.commons.httpclient.*;  
                                                                                 import org.apache.commons.httpclient.methods.PostMethod;  
                                                                                 import org.apache.commons.httpclient.methods.StringRequestEntity;  
                                                                                 import org.apache.commons.httpclient.methods.multipart.*;  
                                                                                 import com.fasterxml.jackson.*;  
                                                                                 import com.fasterxml.jackson.databind.ObjectMapper;  
                                                                                 public class FileUploadJSON {  
                                                                                       * @param args  
                                                                                       * @throws IOException   
                                                                                       * @throws HttpException   
                                                                                      public static void main(String[] args) throws HttpException, IOException {  
                                                                                           // TODO Auto-generated method stub  
                                                                                           String oauthToken = "00DQ0000001f30k!ARcAQN3Ym5pgUh4B_BaeM7.hhfEyyyyTaJdjETZiDqivz90wbNlduK5qNfk3OTGnVhmufE3JcT23wUrOxECAHzIE_H";  
                                                                                           String url = "";  
                                                                                           //String text = "I love posting files to Chatter!";  
                                                                                           Map<String, List<Map<String, String>>> messageSegments = new HashMap<String, List<Map<String, String>>>();  
                                                                                           Map<String, Map<String, List<Map<String, String>>>> json = new HashMap<String, Map<String, List<Map<String, String>>>>();  
                                                                                           Map<String, Map<String,String>> attch = new HashMap<String, Map<String,String>>();  
                                                                                           List<Map<String, String>> segments = new LinkedList<Map<String, String>>();  
                                                                                           Map<String, String> s = new HashMap<String, String>();  
                                                                                           s.put("id", "00570000001bCyB");  
                                                                                           Map<String, String> s1 = new HashMap<String, String>();  
                                                                                           s1.put("text", "Will it mention?");            
                                                                                           messageSegments.put("messageSegments", segments);  
                                                                                           Map<String, String> s2 = new HashMap<String, String>();  
                                                                                           s2.put("attachmentType", "NewFile");  
                                                                                           s2.put("description", "API Test");  
                                                                                           s2.put("title", "Content File 1");  
                                                                                           attch.put("attachment", s2);  
                                                                                           json.put("body", messageSegments);  
                                                                                           ObjectMapper mapper=new ObjectMapper();  
                                                                                           String totalString = "{ \"body\":"+mapper.writeValueAsString(messageSegments) + ", " + mapper.writeValueAsString(attch).substring(1,mapper.writeValueAsString(attch).length()-1)+"}";  
                                                                                           File contentFile = getFile();  
                                                                                           StringPart jsonPart1=new StringPart("json",totalString);  
                                                                                           FilePart filePart= new FilePart("feedItemFileUpload", contentFile);  
                                                                                           Part[] parts = {              
                                                                                           final PostMethod postMethod = new PostMethod(url);  
                                                                                           try {             
                                                                                            //postMethod.setRequestEntity(new StringRequestEntity(mapper.writeValueAsString(json), "application/json", "UTF-8"));  
                                                                                            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));  
                                                                                            postMethod.setRequestHeader("Authorization", "OAuth " + oauthToken);  
                                                                                            postMethod.addRequestHeader("X-PrettyPrint", "1");  
                                                                                            HttpClient httpClient = new HttpClient();   
                                                                                            int returnCode = httpClient.executeMethod(postMethod);  
                                                                                            // System.out.println("Expected return code of: " + HttpStatus.SC_CREATED, returnCode == HttpStatus.SC_CREATED);  
                                                                                           } finally {  
                                                                                      private static File getFile() {  
                                                                                           // TODO Auto-generated method stub  
                                                                                           File file = new File("C:\\Users\\Desktop\\Predictor\\Simple Works.pdf");  
                                                                                           return file;  

                                                                              You Might Also Like


                                                                              Popular Posts