Below is a form:
A direction in which you can attain making a multiform-data call could be as follows:
BodyProcessor can be used with their default implementations or else a custom implementation can also be used. Few of the ways to use them are :
Read the processor via a string as :
HttpRequest.BodyProcessor dataProcessor = HttpRequest.BodyProcessor.fromString("{\"username\":\"foo\"}")
Creating a processor from a file using its path
Path path = Paths.get("/path/to/your/file"); // in your case path to 'img'
HttpRequest.BodyProcessor fileProcessor = HttpRequest.BodyProcessor.fromFile(path);
OR
You can convert the file input to a byte array using the apache.commons.lang
(or a custom method you can come up with) to add a small util like :
org.apache.commons.fileupload.FileItem file;
org.apache.http.HttpEntity multipartEntity = org.apache.http.entity.mime.MultipartEntityBuilder.create()
.addPart("username",new StringBody("foo", Charset.forName("utf-8")))
.addPart("img", newFileBody(file))
.build();
multipartEntity.writeTo(byteArrayOutputStream);
byte[] bytes = byteArrayOutputStream.toByteArray();
and then the byte[] can be used with BodyProcessor
as:
HttpRequest.BodyProcessor byteProcessor = HttpRequest.BodyProcessor.fromByteArray();
Further, you can create the request as :
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http:///example/html5/demo_form.asp"))
.headers("Content-Type","multipart/form-data","boundary","boundaryValue") // appropriate boundary values
.POST(dataProcessor)
.POST(fileProcessor)
.POST(byteProcessor) //self-sufficient
.build();
The response for the same can be handled as a file and with a new HttpClient
using
HttpResponse.BodyHandler bodyHandler = HttpResponse.BodyHandler.asFile(Paths.get("/path"));
HttpClient client = HttpClient.newBuilder().build();
as:
HttpResponse response = client.send(request, bodyHandler);
System.out.println(response.body());