logo

NJP

Script to send multipart (including text and binary) RestAPI

Import · Nov 03, 2021 · article

I've successfully submitted a multi-part Rest API, so I'll post an example Script.This Script is sent using an attachment as a multi-part body.

Attachments are multi-part data that includes text and binary data. Examples include JSON and PDF.

I use "ByteArrayOutputStream" and "GlideSysAttachment.write" to create attachments.

It does not use "MultipartHelper". It only works with the example Script.

To execute the example Script, create the following Script in sys_script_fix (or Script include), rewrite the SYSID to it. (attachmentTableSysid)

Next, rewrite the SYSID of the PDF to be sent. (pdfAttachmentSysid)

Please rewrite and execute according to your instance.

Thank you.

--- Note --- I've used FlowDesigner's multipart and have failed to create complex transmissions containing text and binaries. So I used the example Script to send the multipart as a single attachment and it finally succeeded.

// Example RestAPI Multi part body 
var bodyList = [
    // Please set the characters and data you want to send
    '--xXxxxxxxxxxxxxxxxxXx',
    'Content-Type: application/json; charset=UTF-8',
    'Content-Disposition: form-data; name="metadata"',
    '',
    // Example JSON
    JSON.stringify({
        "name": "ExamplePDF.pdf",
        "mimeType": "application/pdf",
        "parents": "folder_id"
    }),
    '',
    '--xXxxxxxxxxxxxxxxxxXx',
    'Content-Type: application/pdf',
    'Content-Disposition: form-data; name="file"',
    '',
    // Example PDF Binary Data
    function(byteOutStrm) {
        var pdfAttachmentSysid = 'ae95a9522f233010828ad6c6f699b638';
        var attaInStrm = new GlideSysAttachmentInputStream(pdfAttachmentSysid);
        attaInStrm.writeTo(byteOutStrm, 0, 0);
    },
    '',
    '--xXxxxxxxxxxxxxxxxxXx--'
];
// Create a byte array output stream
var byteOutStrm = new Packages.java.io.ByteArrayOutputStream();
for (var i = 0; i < bodyList.length; i++) {
    if (typeof bodyList[i] != 'function') {
        var bytes = Packages.java.lang.String('' + bodyList[i] + '\n').getBytes();
        byteOutStrm.write(bytes, 0, bytes.length);
    } else {
        bodyList[i].call(this, byteOutStrm);
    }
}
// Create an attachment from a byte array 
var attachment = new GlideSysAttachment();
// Table for storing work data. (any)
var attachmentTable = 'sys_script_fix';
var attachmentTableSysid = 'd07269162f233010828ad6c6f699b6bd';
var grAttachment = new GlideRecord(attachmentTable);
grAttachment.get(attachmentTableSysid);
var byteArray = byteOutStrm.toByteArray();
/*
# GlideSysAttachment.write
# Create an attachment.
# (GlideRecord, File Name, Content Type, Data)
*/
var attachmentSysID = attachment.write(grAttachment, 'PostBody', 'application/octet-stream', byteArray);
var attachmentLength = byteArray.length;
byteArray = null;

// Example RestAPI Multi part
if (attachmentSysID) {
    var request = new sn_ws.RESTMessageV2();
    request.setRequestHeader("Accept", "Application/json");
    request.setRequestHeader("Content-Type", 'multipart/related; boundary="xXxxxxxxxxxxxxxxxxXx"');
    request.setRequestHeader("Content-length", '' + attachmentLength);
    var authId = 'AccountID';
    var authPassword = 'Password';
    request.setBasicAuth(authId, authPassword);
    request.setHttpMethod('post');

    // simple HTTP Request & Response Service. (https://httpbin.org)
    request.setEndpoint('https://httpbin.org/post');

    // Set Request Body From Attachment
    request.setRequestBodyFromAttachment(attachmentSysID);
    // Save Response Body As Attachment
    request.saveResponseBodyAsAttachment(attachmentTable, attachmentTableSysid, 'ResponseJSON.txt');
    // Sending a request
    var response = request.execute();
    var statusCode = response.getStatusCode();
    gs.info('statusCode ' + statusCode);
}

Labels:

image

View original source

https://www.servicenow.com/community/developer-articles/script-to-send-multipart-including-text-and-binary-restapi/ta-p/2315271