Creating a body from InputStream can be accomplished using BodyPublishers.ofInputStream(), as shown in the following snippet of code (here, we rely on ByteArrayInputStream but, of course, any other InputStream is suitable):
HttpRequest requestBodyOfInputStream = HttpRequest.newBuilder()
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofInputStream(()
-> inputStream("user.json")))
.uri(URI.create("https://reqres.in/api/users"))
.build();
private static ByteArrayInputStream inputStream(String fileName) {
try (ByteArrayInputStream inputStream = new ByteArrayInputStream(
Files.readAllBytes(Path.of(fileName)))) {
return inputStream;
} catch (IOException ex) {
throw new RuntimeException("File could not be read", ex);
}
}
In order to take advantage of lazy creation, InputStream has to be passed as Supplier.