【问题标题】:Can HTTP multipart and chunking coexist?HTTP 多部分和分块可以共存吗?
【发布时间】:2012-04-30 19:25: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(boolean)”选项。

我的问题是:

  1. HTTP 多部分和分块可以根据协议规范共存吗?如果没有,为什么像InputStreamEntity 类这样的其他实体有setChunked(boolean)MultipartEntity 没有?

  2. 有没有办法在启用分块的情况下“一次”发布多个文件,最好是使用 apache 库?

【问题讨论】:

    标签: java http chunked-encoding http-chunked multipartentity


    【解决方案1】:

    为我的第二个问题找到了解决方案,诀窍是将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);
    

    【讨论】:

      猜你喜欢
      • 2014-07-09
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      相关资源
      最近更新 更多