Skip to content
Advertisement

How to send a PUT request with multipart/form-data body with Java Http Client?

I am using the HttpClient and HttpRequest available on java.net.http. I have successfully sent some GET and POST requests, but I have no clue about how to send a PUT/POST request with multipart/form-data body:

HttpRequest dataRequest = HttpRequest.newBuilder()
        .header("accept", "*/*")
        .header("Content-Type", "multipart/form-data")
        // .POST() ??
        .uri(URI.create(DATA_URL)
        .build();

The curl equivalent of this request would be something like:

curl -X PUT "https://www.example.com/data" -H  "accept: */*" -H  "Content-Type: multipart/form-data" -F "file=@audiofile.wav;type=audio/wav"

Should I use some kind of BodyPublishers in the POST() or PUT() method in order to achieve that? Any clue?

Advertisement

Answer

Multipart/form-data is not supported out of the box by the HttpClient API yet.

In JDK 16 there is a new HttpRequest.BodyPublishers.concat(BodyPublisher...) method that can be used to help build a request body built from the concatenation of bytes coming from heterogeneous sources. But you would have to manually compose all the different parts, and handle base64 encoding when/if that’s needed.

You could also try out methanol

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement