+ Start a Discussion
Arul Bernard I 14Arul Bernard I 14 

How to get attachments from salesforce using java and REST web service


I need to retrieve the attachment from Salesforce using java. Can anyone help me out with the solution
Hi Arul,

Please try below code.

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;

import com.sforce.soap.enterprise.Connector;
import com.sforce.soap.enterprise.EnterpriseConnection;
import com.sforce.soap.enterprise.QueryResult;
import com.sforce.soap.enterprise.sobject.Attachment;
import com.sforce.ws.ConnectionException;
import com.sforce.ws.ConnectorConfig;

public class AttachmentQuery {
    public static void main(String[] args) throws NumberFormatException, IOException, URISyntaxException {
       //Create a new connectionconfig to your Salesforce Org
        ConnectorConfig sfconfig = new ConnectorConfig();
        //Use your salesforce username = email
        //Use your saleforce password with your security token look like: passwordjeIzBAQKkR6FBW8bw5HbVkkkk
        EnterpriseConnection partnercon = null;
        try {
            // create a salesforce connection object with the credentials supplied in your connectionconfig
            partnercon = Connector.newConnection(sfconfig);
            QueryResult describeGlobalResult = partnercon.query("selectName, Body from Attachment where ContentType='application/pdf'");
        } catch (ConnectionException e) {
        // TODO Auto-generated catch block

Please mark best if it helps you. Thanks in advance.

Pawan Kumar
Arul Bernard I 14Arul Bernard I 14
Thanks Pawan,

But actually. I want to know how to write Apex web service to retrieve an attachment 
You mean you want to expose your web services on salesforce where you will be retrieving the attachment from other locations(not salesforce attachment). am I right?
Arul Bernard I 14Arul Bernard I 14
Need to Create an Apex REST class which contains methods to retrieve attachments from custom object
Arul Bernard I 14Arul Bernard I 14
This is the sample code which I look like fro but this will work?? !!
global with sharing class AccountManager
   @HttpGet global static Account getCAccountById()
RestRequest request = RestContext.request;
accId = request.requestURI.substring( request.requestURI.lastIndexOf('/')+1);
List<Attachment> att=[Select a.Id,a.ContentType,a.ParentId,a.Parent.Type,a.Parent.Name,a.BodyLength From Attachment ];  
return result;