2012-04-19 55 views
7

我正在使用apache HttpClient幾個文件到服務器。下面的代碼:HTTP multipart和chunking可以共存嗎?

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庫?

回答

8

得到了一個解決方案,我的第二個問題,關鍵是要編寫MultipartEntityByteArrayOutputStream,創建一個ByteArrayOutputStreamByteArrayEntity啓用分塊上。這裏的代碼:

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); 
相關問題