Can HTTP multipart and chunking coexist?

心不动则不痛 提交于 2019-11-29 03:28:09

问题


I'm using apache HttpClient to post several files to server. Here's the code:

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

The problem is, MultipartEntity class only has isChunked() method (which always returns false), there is no "setChunked(boolean)" option if I wish to enable chucked encoding for my multipart entity.

My question is:

  1. Can HTTP multipart and chunking coexist according to protocol specification? If not, why other entities like InputStreamEntity class have setChunked(boolean) where MultipartEntity doesn't?

  2. Is there any way to post multiple files "at once" with chunking enabled, more preferably with apache libraries?


回答1:


Got a solution for my second question, the trick is to write MultipartEntity to a ByteArrayOutputStream, create a ByteArrayEntity from ByteArrayOutputStream and enable chunking on that. Here's the the code:

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


来源:https://stackoverflow.com/questions/10225396/can-http-multipart-and-chunking-coexist

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