Java HttpClient Upload File Example

In this source code example, we will write a Java program that uses HTTP Client API to upload a resource.

We will use Java 11 HttpClient API to upload a resource file.

Java HttpClient Upload File Example

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException, InterruptedException {

        Map<Object, Object> data = new LinkedHashMap<>();
        data.put("author", "Lorem Ipsum Generator");
        data.put("filefield", Path.of("sample.txt"));
        String boundary = UUID.randomUUID().toString().replaceAll("-", "");

        HttpClient client = HttpClient.newHttpClient();

        HttpRequest request = HttpRequest.newBuilder()
                .header("Content-Type", "multipart/form-data;boundary=" + boundary)
                .POST(ofMultipart(data, boundary))
                .uri(URI.create("http://jkorpela.fi/cgi-bin/echoraw.cgi"))
                .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println("Status code: " + response.statusCode());
        System.out.println("\n Body: " + response.body());
    }

    private static final String LINE_SEPARATOR = System.lineSeparator();

    public static HttpRequest.BodyPublisher ofMultipart(
            Map<Object, Object> data, String boundary) throws IOException {

        final byte[] separator = ("--" + boundary + LINE_SEPARATOR
                + "Content-Disposition: form-data; name=").getBytes(StandardCharsets.UTF_8);
        final List<byte[]> body = new ArrayList<>();

        for (Object dataKey : data.keySet()) {
            body.add(separator);

            Object dataValue = data.get(dataKey);

            if (dataValue instanceof Path) {
                Path path = (Path) dataValue;

                String mimeType = fetchMimeType(path);

                body.add(("\"" + dataKey + "\"; filename=\"" + path.getFileName()
                        + "\"" + LINE_SEPARATOR + "Content-Type: "
                        + mimeType + LINE_SEPARATOR + LINE_SEPARATOR)
                        .getBytes(StandardCharsets.UTF_8));

                body.add(Files.readAllBytes(path));

                body.add(LINE_SEPARATOR.getBytes(StandardCharsets.UTF_8));
            } else {
                body.add(("\"" + dataKey + "\""
                        + LINE_SEPARATOR + LINE_SEPARATOR + dataValue + LINE_SEPARATOR)
                        .getBytes(StandardCharsets.UTF_8));
            }
        }

        body.add(("--" + boundary + "--").getBytes(StandardCharsets.UTF_8));

        return HttpRequest.BodyPublishers.ofByteArrays(body);
    }

    private static String fetchMimeType(Path filenamePath) throws IOException {
        String mimeType = Files.probeContentType(filenamePath);

        if (mimeType == null) {
            throw new IOException("Mime type could not be fetched");
        }

        return mimeType;
    }
}




Comments