I am trying to migrate from normal HttpPost methods to Spring WebClient and I have an API that accepts two files (one JSON and one PDF) for upload.
I am trying to send the files like below, but getting a 500 Internal Server Error instead of the 200 OK.
String jsonData ="";
ByteArrayOutputStream file;
MultipartBodyBuilder builder = new MultipartBodyBuilder();
String header1 = String.format("form-data; name=%s; filename=%s", "attach", "file.pdf");
String header2 = String.format("form-data; name=%s; filename=%s", "jsonfile", "jsonfile.json");
// This line is causing the problem, Am I making a mistake here?
builder.part("attach", file.toByteArray()).header("Content-Disposition", header1);
// This line works fine.
builder.part("jsonfile", jsonData.getBytes()).header("Content-Disposition", header2);
WebClient webClient = WebClient.create("a url");
byte[] fileContent = null;
try {
fileContent = webClient.post()
.body(BodyInserters.fromMultipartData(builder.build()))
.retrieve()
.onStatus(HttpStatus::isError, res -> handleError(res))
.bodyToMono(byte[].class)
.block();
} catch (Exception e) {
return null;
}
However, If I do not send the PDF file in the request, it works fine with only the JSON file. With the Postman both cases work fine.
I assume that I am making a mistake when adding the PDF file to the request. Though the file itself is a valid PDF, and the response of the API is a JSON file.
If someone could tell me what could possibly be wrong here.