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 |
- 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.
- Paste this URL in chrome
- 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.
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
"type": "mention",
"id" : "005D0000001GpHp"
}, {
- 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
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
Post a Comment
Feedback - positive or negative is welcome.