-3

I am struggling to configure body for http request.

This is what I have received from integration team.

"body": {
    "mode": "formdata",
    "formdata": [
        {
            "key": "sourceFile",
            "type": "file",
            "src": "",   /// PDF or CSV file.
            "disabled": true
        }
    ]
}

I don't have issue with API. I am not sure how to set additional params in body; when sending response its says sourcefile is missing. This is what I have tried:

String boundary = 'DUMMY'; String header = '--'+boundary+'\r\nContent-Disposition: form-data; name="file"; filename="'+file_name+'"\r\nContent-Type: application/octet-stream';
// added '\r's removed ';' see Tim Smith's comment
String footer = '\r\n--'+boundary+'--';
String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));

and merging with body contains csv or pdf file.

closed as off-topic by glls, Pranay Jaiswal, Raul, Himanshu, Mohith Shrivastava Dec 14 '18 at 14:49

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Programming questions not specific to Salesforce are off-topic here, but can be asked on Stack Overflow." – glls, Pranay Jaiswal, Himanshu, Mohith Shrivastava
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 5
    What have you tried so far? Where are you stuck? If you take a look at the docs for HttpRequest, you'll find the relevant API. – David Reed Dec 7 '18 at 0:42
2

You could do something like this:

Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('you endpoint');
request.setMethod('POST');

String body = '"mode": "formdata", ' +
              '  "formdata": [ ' +
              '        { ' +
              '            "key": "sourceFile", ' +
              '            "type": "file", ' +
              '              "src": "...",   ' +
              '            "disabled": true' +
              '        }' +
              '      ]';
request.setBody(body);
HttpResponse response = http.send(request);

You can also create a Body object and use JSON class to serialize it. For example:

 public class Body {
      public String key;
      public String myType;
      public String src

 }

and use it in request body:

 Body reqBody = new Body();
 //set values 
 reqBody.src = EncodingUtil.base64Encode(Blob.valueOf());

 request.setBody(JSON.serialize(reqBody));

Please also note that there is limit in object size if you want to serialize it.

  • Thanks kvor; i did similar with minor change in params only and manage to upload file. – Raj Mav3rik Dec 11 '18 at 3:42
2

Trailhead has a great module which I would recommend you take:

It has the code samples you are looking for, alongside simple explanations. If you are still unable to send a body alongside your request, I would then suggest you update your post with your exact problem alongside the error being returned, this will increase the likelyhood of being assisted on the forum.

2

Based on the additional information you have provided, the service you're calling is not a JSON REST service, but expects a multipart form data body. The JSON you included in your question appears to be a specification for that body.

It appears to me that the issue is that you're not setting a sourceFile key in the multipart/form data body that you are constructing, which your remote service is looking for.

Presumably, you should be setting the name value to sourceFile in the part for your file, although only your integration developers can make that entirely clear to you. It's hard to see what other issues might be present in the body you are generating without a more complete example, and in the end this question has more to do with the specific requirements of the integration with which you are working than it does with Salesforce.

0

Here is example of the code that is working for me:

@future(callout=true)
    public static void BankAccountCSVFile_HTTPCallout(){

        String file_name = 'mav3rik12.csv'; 
        Set<Id> setBillingAccountIds = new set<Id>();
        setBillingAccountIds.add('RecordId');
        SageBankAccountGenerateCSV csv = new SageBankAccountGenerateCSV();
        String file_body = csv.BankAccountCreateCSV(setBillingAccountIds);

        String boundary = '----------------------------741e90d31eff';

        String header = '--'+boundary+'\nContent-Disposition: form-data; name="sourceFile"; filename="'+Utilities.BANK_ACCOUNT_CSV_FILENAME+'";\nContent-Type: application/octet-stream';
        String footer = '--'+boundary+'--';             
        String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));

        while(headerEncoded.endsWith('='))
        {
            header+=' ';
            headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
        }
        String bodyEncoded = EncodingUtil.base64Encode(blob.valueOf(file_body));

        Blob bodyBlob = null;
        String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());

        if(last4Bytes.endsWith('==')) {
            last4Bytes = last4Bytes.substring(0,2) + '0K';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
        } else if(last4Bytes.endsWith('=')) {
            last4Bytes = last4Bytes.substring(0,3) + 'N';
            bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
            footer = '\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);              
        } else {
            footer = '\r\n' + footer;
            String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
            bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);  
        }

        HttpRequest req = new HttpRequest();
        req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
        req.setMethod(CatchUtilities.HTTP_POST);
        req.setEndpoint(sENDPOINT);
        req.setHeader('authKey', 'XXXXXXXXXXXXXX');
        req.setBodyAsBlob(bodyBlob);
        req.setTimeout(120000);

        Http http = new Http();
        HTTPResponse res = http.send(req);
    } 
  • 1
    please do not post code dumps without an explanation – glls Feb 15 at 2:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.