π Binary Transmission, Boundary Delimiters & Stream Verification
While standard REST endpoints exchange text-based JSON or XML payloads, enterprise architectures frequently require transmitting binary documents, media assets, identity documents, and spreadsheet exports. Under HTTP standards (RFC 7578), file uploads rely on the multipart/form-data media type. Instead of a uniform body, the HTTP message is divided into multiple distinct payload segments separated by unique cryptographic boundary delimiters. Each sub-part maintains its own Content-Disposition, Content-Type, and binary or textual body stream. REST Assured simplifies this complex protocol via the multiPart() API and MultiPartSpecBuilder, allowing engineers to combine raw binary files (such as PDF transcripts or JPEG profile avatars) with structured JSON metadata in a single atomic transaction, while enabling byte-level assertions and cryptographic hash verifications on downloaded server files.
MULTIPART/FORM-DATA HTTP WIRE STREAM ARCHITECTURE:
POST /v1/students/STU-88219/documents HTTP/1.1
Host: staging-api.nikita-infotech.com
Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575
-----------------------------974767299852498929531610575
Content-Disposition: form-data; name="documentMetadata"
Content-Type: application/json; charset=UTF-8
{"documentType": "CERTIFICATE", "issuer": "Nikita Infotech", "year": 2026}
-----------------------------974767299852498929531610575
Content-Disposition: form-data; name="file"; filename="candidate_transcript.pdf"
Content-Type: application/pdf
%PDF-1.4 ... [RAW BINARY OCTET STREAM DATA] ... %%EOF
-----------------------------974767299852498929531610575
Content-Disposition: form-data; name="verificationTag"
Content-Type: text/plain
OFFICIAL_VERIFIED
-----------------------------974767299852498929531610575--
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β WIRE PROTOCOL HIGHLIGHTS: β
β βββ Boundary Delimiter: Cryptographic boundary string declared in the master Content-Type β
β βββ Part 1 (JSON Form): Metadata describing the asset, parsed by Jackson/Spring @RequestPart β
β βββ Part 2 (Binary File): File byte stream with original filename and specific MIME type β
β βββ Part 3 (Text Field): Simple form scalar value β
β βββ Terminal Boundary: Double hyphen suffix (--) signaling EOF to the server socket parser β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
java.io.File reference to the standard multiPart() DSL method, asserting successful upload status, and validating returned file metadata.
package com.nikita.restassured.binary;
import org.testng.annotations.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.*;
public class BasicFileUploadTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Upload single PDF transcript document via multiPart(File)")
public void testSinglePdfUpload() {
// Reference target file from test resources or temp directory
File uploadFile = new File("src/test/resources/fixtures/candidate_transcript.pdf");
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
// Form control name "file" bound to File instance
.multiPart("file", uploadFile)
.log().ifValidationFails()
.when()
.post("/students/STU-88219/documents/upload")
.then()
.log().ifValidationFails()
.statusCode(201)
.body("status", equalTo("UPLOADED"))
.body("data.fileName", equalTo("candidate_transcript.pdf"))
.body("data.mimeType", equalTo("application/pdf"))
.body("data.fileSizeBytes", greaterThan(0))
.body("data.downloadUrl", startsWith("https://"));
System.out.println("[β] Single PDF transcript uploaded and verified successfully.");
}
}
MultiPartSpecBuilder to specify explicit MIME types (e.g., image/jpeg), custom part headers, and original wire filenames for precise gateway acceptance.
package com.nikita.restassured.binary;
import io.restassured.builder.MultiPartSpecBuilder;
import io.restassured.specification.MultiPartSpecification;
import org.testng.annotations.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class MultiPartSpecBuilderTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Upload profile avatar image using strongly-typed MultiPartSpecBuilder")
public void testAvatarUploadWithCustomSpec() {
File avatarImage = new File("src/test/resources/fixtures/avatar_profile.jpg");
// Construct strongly-typed multi-part specification
MultiPartSpecification multiPartSpec = new MultiPartSpecBuilder(avatarImage)
.controlName("profileAvatar") // Form input element name
.fileName("custom_student_avatar.jpg") // Wire file name passed to server
.mimeType("image/jpeg") // Explicit MIME representation
.charset("UTF-8")
.build();
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
// Attach customized MultiPartSpecification
.multiPart(multiPartSpec)
.when()
.post("/students/STU-88219/avatar")
.then()
.statusCode(200)
.body("status", equalTo("AVATAR_UPDATED"))
.body("data.fileName", equalTo("custom_student_avatar.jpg"))
.body("data.detectedMime", equalTo("image/jpeg"));
System.out.println("[β] Avatar uploaded with explicit MIME type and wire filename.");
}
}
@RequestPart).
package com.nikita.restassured.binary;
import org.testng.annotations.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class MixedMultipartPayloadTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Upload file along with JSON metadata part in single atomic request")
public void testMixedJsonAndFileUpload() {
File documentFile = new File("src/test/resources/fixtures/candidate_transcript.pdf");
// Structured JSON payload representing metadata part
String documentMetadataJson = "{\n" +
" \"documentCategory\": \"ACADEMIC_TRANSCRIPT\",\n" +
" \"verifiedBy\": \"SDET_ADMISSIONS_LEAD\",\n" +
" \"securityClassification\": \"CONFIDENTIAL\"\n" +
"}";
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
// Part 1: JSON Metadata (Specifying "application/json" as the MIME type for this part)
.multiPart("metadata", documentMetadataJson, "application/json")
// Part 2: Binary File
.multiPart("file", documentFile, "application/pdf")
// Part 3: Simple string form parameter
.multiPart("retentionYears", "5")
.when()
.post("/students/STU-88219/documents/composite")
.then()
.statusCode(201)
.body("status", equalTo("RECORD_PROVISIONED"))
.body("data.category", equalTo("ACADEMIC_TRANSCRIPT"))
.body("data.fileAttached", equalTo(true));
System.out.println("[β] Composite request (JSON metadata + PDF file) processed atomically.");
}
}
multiPart() declarations with identical control names (e.g. files) to upload an array of documents to the server.
package com.nikita.restassured.binary;
import org.testng.annotations.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class MultiFileUploadTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Upload multiple files in a single request using array control naming")
public void testBatchMultiFileUpload() {
File transcriptPdf = new File("src/test/resources/fixtures/candidate_transcript.pdf");
File certificatePdf = new File("src/test/resources/fixtures/degree_certificate.pdf");
File idProofJpg = new File("src/test/resources/fixtures/government_id.jpg");
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
// Chaining multiple .multiPart() calls with the same control name "attachments"
// creates an array payload parsed by servers as List
.multiPart("attachments", transcriptPdf, "application/pdf")
.multiPart("attachments", certificatePdf, "application/pdf")
.multiPart("attachments", idProofJpg, "image/jpeg")
.multiPart("batchTrackingCode", "BATCH-DOCS-2026-PUNE")
.when()
.post("/students/STU-88219/documents/batch")
.then()
.statusCode(200)
.body("status", equalTo("BATCH_ACCEPTED"))
.body("data.totalFilesProcessed", equalTo(3))
.body("data.uploadedFiles[0].name", equalTo("candidate_transcript.pdf"))
.body("data.uploadedFiles[1].name", equalTo("degree_certificate.pdf"))
.body("data.uploadedFiles[2].name", equalTo("government_id.jpg"));
System.out.println("[β] Multi-file batch upload (3 files) verified in single HTTP transaction.");
}
}
byte[] arrays and InputStream references using multiPart().
package com.nikita.restassured.binary;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class InMemoryStreamUploadTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Upload dynamically generated CSV content as byte array without disk I/O")
public void testByteArrayStreamingUpload() {
// Dynamically synthesize a CSV document in memory
String dynamicCsvContent = "StudentId,FullName,Track,Grade\n" +
"STU-88219,Nikita Sharma,ENTERPRISE_AUTOMATION,A+\n" +
"STU-88220,Aarav Deshmukh,FULLSTACK_SDET,A\n";
byte[] binaryCsvBytes = dynamicCsvContent.getBytes(StandardCharsets.UTF_8);
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
// Method signature: multiPart(String controlName, String fileName, byte[] content, String mimeType)
.multiPart("reportFile", "dynamically_generated_grades.csv", binaryCsvBytes, "text/csv")
.when()
.post("/reports/csv/upload")
.then()
.statusCode(201)
.body("status", equalTo("INGESTED"))
.body("data.recordCount", equalTo(2));
System.out.println("[β] In-memory byte[] stream uploaded cleanly without creating temp disk files.");
}
@Test(description = "Upload binary stream using java.io.InputStream")
public void testInputStreamUpload() {
byte[] rawStreamData = "BINARY_STREAM_PACKET_CONTENT_2026".getBytes(StandardCharsets.UTF_8);
InputStream inputStream = new ByteArrayInputStream(rawStreamData);
given()
.baseUri(BASE_URI)
// Method signature: multiPart(String controlName, String fileName, InputStream stream, String mimeType)
.multiPart("streamPayload", "stream_packet.bin", inputStream, "application/octet-stream")
.when()
.post("/telemetry/stream/upload")
.then()
.statusCode(200);
System.out.println("[β] InputStream streamed directly to server socket.");
}
}
asByteArray() and validating data integrity using cryptographic SHA-256 checksums.
package com.nikita.restassured.binary;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public class FileDownloadValidationTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Download binary PDF file and assert file size and SHA-256 integrity hash")
public void testDownloadAndValidateChecksum() throws NoSuchAlgorithmException, IOException {
// Execute GET request on binary download endpoint
Response downloadResponse = given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
.pathParam("docId", "DOC-TRANSCRIPT-88219")
.when()
.get("/documents/{docId}/download")
.then()
.statusCode(200)
.contentType("application/pdf")
.header("Content-Disposition", equalTo("attachment; filename=\"candidate_transcript.pdf\""))
.extract().response();
// Extract binary payload as raw byte array
byte[] downloadedBytes = downloadResponse.asByteArray();
System.out.println("[*] Downloaded binary payload size: " + downloadedBytes.length + " bytes.");
Assert.assertTrue(downloadedBytes.length > 10000, "Downloaded file payload is unexpectedly small!");
// Assert PDF header magic bytes (%PDF)
String fileHeader = new String(downloadedBytes, 0, 4);
Assert.assertEquals(fileHeader, "%PDF", "Downloaded binary is missing valid %PDF magic header!");
// Compute SHA-256 checksum to verify integrity
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = digest.digest(downloadedBytes);
StringBuilder hexString = new StringBuilder();
for (byte b : hashBytes) {
hexString.append(String.format("%02x", b));
}
String calculatedChecksum = hexString.toString();
System.out.println("[*] Calculated SHA-256 Checksum: " + calculatedChecksum);
// Assert against expected checksum published in server ETag or header
String serverChecksumHeader = downloadResponse.getHeader("X-Checksum-SHA256");
if (serverChecksumHeader != null) {
Assert.assertEquals(calculatedChecksum, serverChecksumHeader, "SHA-256 checksum mismatch!");
}
// Optional: Persist to disk for local audit inspection
try (FileOutputStream fos = new FileOutputStream("target/downloaded_candidate_transcript.pdf")) {
fos.write(downloadedBytes);
}
System.out.println("[β] Verified binary download integrity and persisted artifact to target/.");
}
}
MultiPartConfig within RestAssuredConfig to customize the default boundary string, control character sets, and set the fallback sub-content-type for form parts.
package com.nikita.restassured.binary;
import io.restassured.config.MultiPartConfig;
import io.restassured.config.RestAssuredConfig;
import org.testng.annotations.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
public class MultiPartConfigTest {
@Test(description = "Configure custom MultiPartConfig to control default charset and sub-content-type")
public void testCustomMultiPartConfiguration() {
File uploadFile = new File("src/test/resources/fixtures/candidate_transcript.pdf");
// Custom MultiPartConfig tuning
RestAssuredConfig customConfig = RestAssuredConfig.config()
.multiPartConfig(MultiPartConfig.multiPartConfig()
.defaultCharset("UTF-8")
// Sets the default Content-Type for parts that don't declare one:
.defaultSubContentType("text/plain")
.emptyBoundary());
given()
.config(customConfig)
.baseUri("https://staging-api.nikita-infotech.com/v1")
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
.multiPart("file", uploadFile)
.multiPart("authorNote", "Automated transcript submission")
.when()
.post("/students/STU-88219/documents/upload")
.then()
.statusCode(201);
System.out.println("[β] MultiPartConfig applied globally to outbound stream.");
}
}
HTTP 413 Payload Too Large), submitting unapproved file formats like .exe (HTTP 415), and sending zero-byte empty files.
package com.nikita.restassured.binary;
import io.restassured.builder.MultiPartSpecBuilder;
import org.testng.annotations.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
public class NegativeFileUploadTest {
private static final String BASE_URI = "https://staging-api.nikita-infotech.com/v1";
@Test(description = "Verify server rejects file exceeding 10MB limit with HTTP 413 Payload Too Large")
public void testOversizedFileUploadProduces413() {
// Synthetic 15MB byte array simulating oversized file
byte[] oversizedBytes = new byte[15 * 1024 * 1024];
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
.multiPart(new MultiPartSpecBuilder(oversizedBytes)
.controlName("file")
.fileName("oversized_disk_dump.pdf")
.mimeType("application/pdf")
.build())
.log().ifValidationFails()
.when()
.post("/students/STU-88219/documents/upload")
.then()
.log().ifValidationFails()
// 413 Payload Too Large or 400 Bad Request
.statusCode(413)
.body("title", equalTo("Payload Too Large"))
.body("detail", containsString("Maximum permitted upload size is 10MB"));
System.out.println("[β] 413 Payload Too Large asserted for oversized file upload.");
}
@Test(description = "Verify server rejects executable binary with HTTP 415 Unsupported Media Type")
public void testDangerousFileExtensionProduces415() {
byte[] fakeExeContent = "MZ_FAKE_EXECUTABLE_BINARY_DATA".getBytes();
given()
.baseUri(BASE_URI)
.header("Authorization", "Bearer eyJhbGciOiJIUzI1Ni...")
.multiPart(new MultiPartSpecBuilder(fakeExeContent)
.controlName("file")
.fileName("malicious_script.exe")
.mimeType("application/x-msdownload")
.build())
.when()
.post("/students/STU-88219/documents/upload")
.then()
.statusCode(415)
.body("title", equalTo("Unsupported Media Type"))
.body("detail", containsString("File type 'application/x-msdownload' is forbidden"));
System.out.println("[β] 415 Unsupported Media Type asserted for rejected file format.");
}
}
REST ASSURED MULTIPART & BINARY SPECIFICATION MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββ
β OPERATION TARGET β DSL METHOD SIGNATURE β ARGUMENT TYPES β PRIMARY OPERATIONAL ROLE β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββΌββββββββββββββββββββββββββββββββ€
β Simple File Upload β .multiPart("name", File) β String, File β Uploads file from disk β
β In-Memory byte[] Upload β .multiPart(name, fn, byte[]) β Str, Str, byte[] β Streams byte[] without disk β
β InputStream Upload β .multiPart(name, fn, stream) β Str, Str, Stream β Direct stream to wire socket β
β MultiPartSpecBuilder β .multiPart(MultiPartSpec) β Spec Instance β Custom MIME, charset, control β
β Mixed JSON Metadata Partβ .multiPart(name, json, mime) β Str, Str, Str β Injects JSON part alongside flβ
β Batch Multi-File Upload β Chained .multiPart() calls β Same controlName β Generates file array on wire β
β Binary File Download β response.asByteArray() β N/A (Method) β Extracts raw binary byte[] β
β Binary Stream Download β response.asInputStream() β N/A (Method) β Reads binary stream from wire β
β SHA-256 Hash Validation β MessageDigest.getInstance() β Java Security β Verifies downloaded file checkβ
β MultiPartConfig Tuning β RestAssuredConfig.config().. β MultiPartConfig β Sets default charset/sub-MIME β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββββββββββββββββββββ€
β TOP 5 MULTIPART & BINARY TESTING BEST PRACTICES: β
β 1. Let REST Assured manage the boundary: Never manually set Content-Type: multipart/form-data. β
β 2. Use in-memory byte[] arrays for generated files: Eliminate disk I/O bottlenecks in CI/CD runs. β
β 3. Validate SHA-256 checksums on downloads: Confirm downloaded files are not corrupted in transit. β
β 4. Test file-size limits (HTTP 413): Ensure the server gracefully rejects oversized uploads. β
β 5. Use MultiPartSpecBuilder for mixed payloads: Set application/json explicitly on metadata parts. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ