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();
  }
}

Leave a Reply

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