编程语言
首页 > 编程语言> > java – HTTP multipart和chunking可以共存吗?

java – HTTP multipart和chunking可以共存吗?

作者:互联网

我正在使用apache HttpClient将几个文件发布到服务器.这是代码:

    public static HttpResponse stringResponsePost(String urlString, String content, byte[] image,
        HttpContext localContext, HttpClient httpclient) throws Exception {

    URL url = new URL(URLDecoder.decode(urlString, "utf-8"));
    URI u = url.toURI();

    HttpPost post = new HttpPost();
    post.setURI(u);

    MultipartEntity reqEntity = new MultipartEntity();
    StringBody sb = new StringBody(content, HTTP_CONTENT_TYPE_JSON, Charset.forName("UTF-8"));
    ByteArrayBody ib = new ByteArrayBody(image, HTTP_CONTENT_TYPE_JPEG, "image");

    reqEntity.addPart("interview_data", sb);
    reqEntity.addPart("interview_image", ib);
    post.setEntity(reqEntity);

    HttpResponse response = null;
    response = httpclient.execute(post, localContext);

    return response;
}

问题是,MultipartEntity类只有isChunked()方法(总是返回false),如果我希望为我的multipart实体启用chucked编码,则没有“setChunked(boolean)”选项.

我的问题是:

> HTTP multipart和chunking可以根据协议规范共存吗?如果没有,为什么像InputStreamEntity类这样的其他实体有setChunked(boolean),而MultipartEntity却没有?
>有没有办法在启用分块的情况下“一次”发布多个文件,更优选的是使用apache库?

解决方法:

得到了我的第二个问题的解决方案,诀窍是将MultipartEntity写入ByteArrayOutputStream,从ByteArrayOutputStream创建ByteArrayEntity并在其上启用分块.这是代码:

    ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
    // reqEntity is the MultipartEntity instance
    reqEntity.writeTo(bArrOS);
    bArrOS.flush();
    ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
    bArrOS.close();

    bArrEntity.setChunked(true);
    bArrEntity.setContentEncoding(reqEntity.getContentEncoding());
    bArrEntity.setContentType(reqEntity.getContentType());

    // Set ByteArrayEntity to HttpPost
    post.setEntity(bArrEntity);

标签:java,http,chunked-encoding,multipartentity,http-chunked
来源: https://codeday.me/bug/20191004/1853863.html