Posting a file from Java

sandeep-agrawal edited this page Sep 17, 2012 · 5 revisions
import java.io.File;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.*;

...

String oauthToken = "Input your token here";
String url = "https://na1.salesforce.com/services/data/v22.0/chatter/feeds/user-profile/me/feed-items";
String text = "I love posting files to Chatter!";
File contentFile = getFile();
String desc = "This is a test file that I'm posting.";
String fileName = "contentFile";
Part[] parts = {
    new StringPart("desc", desc),
    new StringPart("fileName", fileName),
    new StringPart("text", text),
    new FilePart("feedItemFileUpload", contentFile),
};

final PostMethod postMethod = new PostMethod(url);
            
try {
  postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
  postMethod.setRequestHeader("Authorization", "OAuth " + oauthToken);
  postMethod.addRequestHeader("X-PrettyPrint", "1");
  HttpClient httpClient = new HttpClient();
  httpClient.getParams().setSoTimeout(60000);
  int returnCode = httpClient.executeMethod(postMethod);
  System.out.println(postMethod.getResponseBodyAsString());
  assertTrue("Expected return code of: " + HttpStatus.SC_CREATED, returnCode == HttpStatus.SC_CREATED);
} finally {
  postMethod.releaseConnection();
}

Can you tell me how we can post images to chatter user?