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


Step 1: Download required files


  • Download the following files from internet
    • httpcomponents-client-4.2.3-bin.zip
    • 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: http://www.google.com) in the following URL. Encode the CallBack URL before passing it as a parameter. 
https://<instance_name>.salesforce.com/services/oauth2/authorize?response_type=token&client_id=<Client_ID_Goes_Here>&redirect_uri=<CallBack_URL>


  • 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
https://na1.salesforce.com/setup/secur/RemoteAccessAuthorizationPage.apexp?source=l86Hcy6qEKtWNqzXVErZDlmcRQs0D_HBE55MLVuP3x8t5wXkyHYyrVx2Xb5JoWzyVOJrnTqMMaWy_Sfomv.j1xklSQ67NPiEbdAN9EqSTtlyQTuT0J6sGYCxxEBUymytEb6FVKEujyXsKzK3DpNAoCkHeQCmRIT8T2L3ZehdpwPLnRIZlGKw7bNfpwOJmlk4r9NDu8Z7OR9OINbszxRBzD96QX4BjlVItSuo3ftBQLrL2nIq9IMvHo_gVw_wG8M7mj2ySe.3l.MkJBNSbqgqrFdD_1wb47QzQ3.B9iTAWrvAhsuzHdYSicN63Udz.ozgMst_9grKjyv7sB_pOn3HAUxevoeaWVsmttTEwRSI1tA%3D%3D
    • Finally the page will take you to CallBack URL providing it with Access Id. Get Access Id from CallBack URL.  

https://www.google.co.in/#access_token=00DQ0000001f30y%21ARcAQERZPayrNLaOZhOXqH0lbrlTF4sV5iwmc6bzH8Y9VP6uhv77gL9.8YZuT8l1d4e4Km7nVosNbanBaXnQxKV16Res7uZl&instance_url=https%3A%2F%2Fcs3.salesforce.com&id=https%3A%2F%2Ftest.salesforce.com%2Fid%2F00DQ0000001f30yMAA%2F005Q0000001ALKCIA4&issued_at=1370413672564&signature=oyJ0fyAQ0HkTDeY1MO4G1YAdw7ied0BLssxHQ9T7ur8%3D&scope=id+api


  • 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 https://github.com/forcedotcom/JavaChatterRESTApi
  • 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.
      OZ7S29JEM_7Ctq1lst2dzoV.owisJc0KacUbDxyae
        Accept: application/json
          User-Agent: Jakarta Commons-HttpClient/3.0.1
            12
              Introducing Chatter REST API Using Chatter API Inputs
                Host: instance_name
                  Content-Length: 978
                    Content-Type: multipart/form-data; boundary=F9jBDELnfBLAVmLNbnLIYibT5Icp0h3VJ7mkI
                      --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."
                                                    }]
                                                      },
                                                        "attachment":
                                                          {
                                                            "attachmentType" : "NewFile",
                                                              "description": "Quarterly review 2012 Q2",
                                                                "title" : "2012_q2"
                                                                  }
                                                                    }
                                                                      --F9jBDELnfBLAVmLNbnLIYibT5Icp0h3VJ7mkI
                                                                        Content-Disposition: form-data; name="feedItemFileUpload"; filename="foo"
                                                                          Content-Type: application/octet-stream; charset=ISO-8859-1
                                                                            This is the content of the file.
                                                                              --F9jBDELnfBLAVmLNbnLIYibT5Icp0h3VJ7mkI--


                                                                              • 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.io.IOException;  
                                                                                 import java.util.HashMap;  
                                                                                 import java.util.LinkedList;  
                                                                                 import java.util.List;  
                                                                                 import java.util.Map;  
                                                                                 import java.util.ArrayList;  
                                                                                 import java.io.File;  
                                                                                 import java.io.IOException;  
                                                                                 import java.io.OutputStream;  
                                                                                 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 = "https://zzz.salesforce.com/services/data/v27.0/chatter/feeds/record/006Q000000BQESF/feed-items";  
                                                                                           //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("type","mention");  
                                                                                           s.put("id", "00570000001bCyB");  
                                                                                           segments.add(s);  
                                                                                           Map<String, String> s1 = new HashMap<String, String>();  
                                                                                           s1.put("type","text");  
                                                                                           s1.put("text", "Will it mention?");            
                                                                                           segments.add(s1);  
                                                                                           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)+"}";  
                                                                                           System.out.print(totalString);  
                                                                                           //mapper.writeValueAsString(json);  
                                                                                           File contentFile = getFile();  
                                                                                           StringPart jsonPart1=new StringPart("json",totalString);  
                                                                                           //Json  
                                                                                           jsonPart1.setContentType("application/json");  
                                                                                           jsonPart1.setCharSet("UTF-8");  
                                                                                           FilePart filePart= new FilePart("feedItemFileUpload", contentFile);  
                                                                                           filePart.setContentType("application/pdf");            
                                                                                           Part[] parts = {              
                                                                                             jsonPart1,              
                                                                                             filePart  
                                                                                           };  
                                                                                           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");  
                                                                                            //postMethod.addRequestHeader("Content-Type","application/json");  
                                                                                            HttpClient httpClient = new HttpClient();   
                                                                                            httpClient.getParams().setSoTimeout(60000);  
                                                                                            //System.out.println(postMethod.getQueryString());  
                                                                                            int returnCode = httpClient.executeMethod(postMethod);  
                                                                                            System.out.println(postMethod.getResponseBodyAsString()+returnCode);  
                                                                                            // System.out.println("Expected return code of: " + HttpStatus.SC_CREATED, returnCode == HttpStatus.SC_CREATED);  
                                                                                           } finally {  
                                                                                            postMethod.releaseConnection();  
                                                                                           }  
                                                                                      }  
                                                                                      private static File getFile() {  
                                                                                           // TODO Auto-generated method stub  
                                                                                           File file = new File("C:\\Users\\Desktop\\Predictor\\Simple Works.pdf");  
                                                                                           return file;  
                                                                                      }  
                                                                                 }  
                                                                                

                                                                              Comments

                                                                              Popular posts from this blog

                                                                              Updating SourceData/ Data Source of the Pivot Table

                                                                              Salesforce.com migration tool - Deploying Weblink and migrating files with special characters

                                                                              Information Architecture - Setup your term store to scale