MultipartEntity: Content-Length for InputStream

风格不统一 提交于 2019-12-05 20:47:52

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.

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