I have to send an HTTP request from my code which sends a PDF file to another backend service, which consumes multipart form data. I have found the following example how to do this: https://stackoverflow.com/a/44461661/19062211 I implemented this approach almost in the same way. Here I extend InputStreamResource
public final class MultipartInputStreamFileResource extends InputStreamResource {
private final String filename;
public MultipartInputStreamFileResourceV1(InputStream inputStream, String filename) {
super(inputStream);
this.filename = filename;
}
@Override
public String getFilename() {
return this.filename;
}
@Override
public long contentLength() throws IOException {
return -1; // we do not want to generally read the whole stream into memory ...
}
}
And here I actually use it (to send post http request with multipart body)
public void sendPdf(byte[] pdf) {
MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
String fileName = "fileName.pdf";
params.add("file", new MultipartInputStreamFileResource(new ByteArrayInputStream(pdf), fileName));
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
String targetUri = "http://foo.bar";
restTemplateClient.postForEntity(targetUri , requestEntity, Void.class);
}
And the question is should I close InputStreamResource (which I extended with MultipartInputStreamFileResource) somewhere or somehow or maybe I should close at least ByteArrayInputStream, which I create above.
I was looking for examples of using this approach and I didn't find any of them where I could see close invocations. But I am not sure that it's safe and won't result in memory or resource leak.
Thank you very much for your time and your answers. I really appriciate it.