Reusable HttpClient Method for Uploading Files with Multipart Entity

This tutorial shows how to encapsulate a reusable Java HttpClient method that builds a multipart/form-data request, iterates over parameters, attaches binary file streams or text parts, and sets the resulting entity on an HttpPost object, with a Linux‑specific note.

FunTester
FunTester
FunTester
Reusable HttpClient Method for Uploading Files with Multipart Entity

Multipart/form-data upload with HttpClient

When testing APIs that accept file uploads, HttpClient requires a multipart/form-data request. The following utility method builds such a request from a HttpPost, a JSON object of parameters, and a File object.

Method signature

public void setMultipartEntityEntity(HttpPost httpPost, JSONObject params, File file)

Parameters

httpPost – the HttpPost instance that will be sent.

params – a JSONObject containing key‑value pairs for the request. The value "file" indicates that the corresponding key should be bound to the file stream.

file – the file to be uploaded.

Implementation details

String fileName = getFileName(file);
InputStream inputStream = null;
try {
    inputStream = new FileInputStream(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Iterator<String> keys = params.keys();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();

while (keys.hasNext()) {
    String key = keys.next();
    String value = params.getString(key);
    if ("file".equals(value)) {
        // Add the file as a binary part
        builder.addBinaryBody(key, inputStream,
                ContentType.create("multipart/form-data"), fileName);
    } else {
        // Add a regular text part
        StringBody body = new StringBody(value,
                ContentType.create("text/plain", Consts.UTF_8));
        builder.addPart(key, body);
    }
}
HttpEntity entity = builder.build();
httpPost.setEntity(entity);

The method uses MultipartEntityBuilder from Apache HttpComponents to assemble the request. For each entry in params, it either adds a binary body (when the value equals the literal string "file") or a text body. The resulting HttpEntity is attached to the HttpPost object.

Note: The code assumes a Unix‑style file path. On Windows, backslashes must be escaped (e.g., C:\\path\\to\\file ) or converted to forward slashes.
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend Developmentfile uploadmultipartHttpClient
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.