Creating a multi-part POST request, eg. for accessing a REST API

I Love Xbase++ (ILX)
The portal for Xbase++ developers worldwide

Till Warweg

Member
Staff member
I am here to help you!
Feb 1, 2021
35
7
8
Customer Identifier
E074775
Some end points expect a multi-part message to be sent for accessing an API, for example, for uploading a file. The following code snippet illustrates how such a request with its associated payload can be created using the HttpClient class.

Note that the exact requirements regarding the encoding of the data, and the HTTP headers that must be defined may vary with the API in question. Consult the documentation of the web service for details.

Xbase++:
//
// Upload a file to a web service running on the local machine. The request's payload must consist of two parts:
//  - A part containing meta information about the file being uploaded ("uploadinfo"). This info is passed as
//    a JSON stream read from the file info.json
//  - A part containing the actual file being uploaded. In this example, this is an invoice read from the file
//    invoice.xml
//
cURL      := "http://localhost:8100/srv/uploads"
cClientId := "121513"
cAuth     := "Q3loZUC1fTkxep2bWNGFHJaTpMV09K1RHhaSTHl1g3X3"
cInfo     := MemoRead( "info.json" )
cInvoice  := MemoRead( "invoice.xml" )

// Create the HTTP client instance and set global request properties, such as the
// request method and authentication details
oHC := HttpClient():new( cURL )
oHC:setMethod("POST")
oHC:httpRequest:addHeader("CLIENT-ID", cClientId )
oHC:httpRequest:addHeader("Authorization", "Basic " + cAuth )
oHC:httpRequest:addHeader("Content-Type", "multipart/form-data" )

// Add first part of the multi-part request body with meta information. Each part
// has an associated name, content type and encoding
oMessagePart := oHC:HttpRequest:addPart()
oMessagePart:addHeader( "Content-Disposition", 'form-data; name="uploadinfo"; filename="info.json"' )
oMessagePart:addHeader( "Content-Type", "application/json" )
oMessagePart:addHeader( "Content-Transfer-Encoding", "binary" )
oMessagePart:setContent( cInfo )

// Create second part of the multi-part request body containing the invoice to be uploaded
oMessagePart := oHC:HttpRequest:addPart()
oMessagePart:addHeader( "Content-Disposition", 'form-data; name="elauploadstream"; filename="invoice.xml"' )
oMessagePart:addHeader( "Content-Type", "application/octet-stream" )
oMessagePart:addHeader( "Content-Transfer-Encoding", "binary" )
oMessagePart:setContent( cInvoice )

cResult := oHC:send()
nCode   := oHC:getStatusCode()

// Validate status code, process response
...
 
Last edited: