How to generate multipart/form-data request body for Apex HTTP Callout

HTTP Callouts are used for integrating external REST-based services with Salesforce. Apex provides three built-in classes to work with HTTP services and create HTTP requests like GET, POST, PUT, and DELETE.

This post demonstrate how to generate multipart/form-data request body using third party apex class.

Code for HttpFormBuilder.apex can be retrived from here.

public class HttpCalloutSample {

  public String executeCallout(recordId, userId) {

    // Instantiate a new http object
    Http h = new Http();

     // Instantiate a new HTTP request, specify the method (POST) as well as the endpoint
    HttpRequest req = new HttpRequest();
    req.setEndpoint('https://testapi.herokuapp.com');
    req.setHeader('Content-Type', HttpFormBuilder.GetContentType());
    req.setMethod('POST');

    // Generate form body
    String body = '';
    body += HttpFormBuilder.WriteBoundary();
    body += HttpFormBuilder.WriteBodyParameter('id', recordId);
    body += HttpFormBuilder.WriteBoundary();
    body += HttpFormBuilder.WriteBodyParameter('userId', userId);
    body += HttpFormBuilder.WriteBoundary(HttpFormBuilder.EndingType.CrLf);

    Blob formBlob = EncodingUtil.base64Decode(body);

    req.setHeader('Content-Length', String.valueOf(formBlob.size()));
    req.setBodyAsBlob(formBlob);

    // Send the request, and return a response
    HttpResponse res = h.send(req);
    return res.getBody();
  }
}

5 Comments

  1. Is there any way to pass an Attachment through as one of the parameters? I am trying to hit the Ocrolus API to send back statements, and that takes in a multipart/form-data request with parameters of an ID, and a file.

    When I try to pass the file through using the HTTPFormBuilder class, it won’t accept the Attachment as a valid input for the “WriteBodyParameter(String, String)” method. If I convert the attachment to string, blob, base64 string and pass that in, the API does not accept it.

  2. How can I create structure like below in Multi-part? I see it takes only key value pair
    “QrInvoice= {
    “creditorInformation”:
    {
    “iban”: “CH3908704016075473007”,
    “creditor”:
    {
    “addressType”: “STRUCTURED”,
    “name”: “Robert Schneider AG”,
    “streetName”: “Rue du Lac”,
    “houseNumber”: “1268/2/22”, “postalCode”: “2501”,
    “city”: “Biel”,
    “addressLine1”: “Rue du Lac 1268/2/22”,
    “addressLine2”: “2501 Biel”,
    “country”: “CH”
    }
    },
    “ultimateCreditor”: {
    “addressType”: “STRUCTURED”,
    “name”: “Robert Schneider Services Switzerland AG”,
    “streetName”: “Rue du Lac”,
    “houseNumber”: “1268/3/1”,
    “postalCode”: “2501”,
    “city”: “Biel”,
    “addressLine1”: “Rue du Lac 1268/3/1”,
    “addressLine2”: “2501 Biel”,
    “country”: “CH”
    },
    “paymentAmountInformation”: {
    “amount”: 199.95,
    “currency”: “CHF”
    },
    “ultimateDebtor”: {
    “addressType”: “STRUCTURED”,
    “name”: “Pia-Maria Rutschmann-Schnyder”,
    “streetName”: “Grosse Marktgasse”,
    “houseNumber”: “28”,
    “postalCode”: “9400”,
    “city”: “Rorschach”,
    “addressLine1”: “Rue du Lac 1268/3/1”,
    “addressLine2”: “2501 Biel”,
    “country”: “CH”
    },
    “paymentReference”: {
    “referenceType”: “SCOR”,
    “reference”: “RF18539007547034”,
    “additionalInformation”: {
    “unstructuredMessage”: “Bill No. 3139 for garden work and disposal of cuttings”,
    “billInformation”: “//S1/10/10201409/11/190512/20/1400.000-53/30/106017086/31/180508/32/7.7/40/2:10;0:30” }
    },
    “alternativeSchemes”: {
    “alternativeSchemeParameters”: [
    “Name AV1: UV;UltraPay005;12345″
    ]
    }
    }”

  3. it is appending some space after the value in the final multipart form.
    for example space after ‘Gaurav Arora’ and after ‘ELA’ which is giving error in case of email id as the email id format dont accept spaces.

    –1ff13444ed8140c7a32fc4e6451aa76d
    Content-Disposition: form-data; name=”atom[name]”

    Q-E00014036-00602140-United Health Group
    –1ff13444ed8140c7a32fc4e6451aa76d
    Content-Disposition: form-data; name=”atom[requester_name]”

    Gaurav Arora
    –1ff13444ed8140c7a32fc4e6451aa76d
    Content-Disposition: form-data; name=”atom[p_contract_type]”

    ELA
    –1ff13444ed8140c7a32fc4e6451aa76d
    Content-Disposition: form-data; name=”atom[requester_email]”

    aroraga@vmware.com
    –1ff13444ed8140c7a32fc4e6451aa76d–

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.