To send files using mlutipart/form-data format in Java, we can utilize Apache HttpClient. This approach is commonly used for file uploads to REST APIs.
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.nio.charset.StandardCharsets;
public class FileUploader {
public static String uploadFile(String apiUrl, File fileToUpload) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost uploadRequest = new HttpPost(apiUrl);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(StandardCharsets.UTF_8);
// Add regular form field
builder.addTextBody("source", "java-upload",
ContentType.TEXT_PLAIN.withCharset("UTF-8"));
// Add file part
builder.addBinaryBody("fileData", fileToUpload,
ContentType.APPLICATION_OCTET_STREAM,
fileToUpload.getName());
uploadRequest.setEntity(builder.build());
HttpResponse response = httpClient.execute(uploadRequest);
return EntityUtils.toString(response.getEntity());
} catch (Exception ex) {
ex.printStackTrace();
return "Upload failed: " + ex.getMessage();
}
}
}
Required Maven dependency:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
Key points:
- Uses MultipartEntityBuilder to construct the multipart request
- Supports both text fields and binary file data
- Handles UTF-8 encoding properly
- Includes proper resource cleanup with try-with-resources