可HTTP多和分块共存?(Can HTTP multipart and chunking coexi

2019-06-23 18:27发布

我使用的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),没有“setChunked(布尔)”选项,如果我想使编码打发我多实体。

我的问题是:

  1. 可根据协议规范HTTP多和组块共存? 如果不是,为什么像其他实体InputStreamEntity类已经setChunked(boolean) ,其中MultipartEntity不?

  2. 有没有办法用Apache库发布多个文件“毕其功于一役”与分块启用,更好?

Answer 1:

有一个解决方案,我的第二个问题,关键是要编写MultipartEntityByteArrayOutputStream ,创建ByteArrayEntityByteArrayOutputStream ,使分块上。 这里的代码:

    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);


文章来源: Can HTTP multipart and chunking coexist?