简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM