MultipartEntity: Content-Length for InputStream

ⅰ亾dé卋堺 提交于 2019-12-07 15:00:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/32998854/multipartentity-content-length-for-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!