Search code examples
javaapache-httpcomponents

MultipartEntity: Content-Length for InputStream


I'm trying to send the data from an inputstream in a multipart/form-data, as a file-parameter using:

MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", inputStream)
            .build();

the problem is that the server seems to require a Content-Length header. I know the correct size of my inputStream - can I set it manually?


Solution

  • Instead of using the addBinaryBody method, you can create your own FormBodyPart with a ContentBody. The appropriate ContentBody is InputStreamBody but its getContentLength method returns -1.

    I'd suggest you extend the class to provide a custom content length.

    class KnownSizeInputStreamBody extends InputStreamBody {   
        private final long contentLength;
    
        public KnownSizeInputStreamBody(InputStream in, long contentLength, ContentType contentType) {
            super(in, contentType);
            this.contentLength = contentLength;
        }
    
        @Override
        public long getContentLength() {
            return contentLength;
        }
    }
    

    You can then create your multipart entity as

    FormBodyPart bodyPart = FormBodyPartBuilder.create().setName("file")
            .setBody(new KnownSizeInputStreamBody(inputStream, contentLenth, ContentType.APPLICATION_OCTET_STREAM)).build();
    
    HttpEntity entity = MultipartEntityBuilder.create().addPart(bodyPart).build();
    

    as appropriate (your own content type, content length, name, etc.).

    In my case, the http client wrote the content-length for the entire multipart request body, not for each part.