2014-01-09 46 views
2

我有一個發送分塊數據的客戶端。我的服務器預計會讀取這些數據。在服務器上,我使用的是Tomcat 7.0.42,並希望通過現有的servlet加載這些數據。閱讀分塊數據

我正在查找谷歌,看看我是否可以得到任何讀取分塊數據的例子,不幸的是我還沒有偶然發現任何。

我發現了Apache Http Client提供的ChunkedInputStream或Tomcat提供的ChunkedInputFilter的少量引用。但我找不到任何有關如何最好地使用這些的體面的例子。

如果你們中的任何人有閱讀/分析分塊數據的經驗,請分享圍繞這些的指針。

Java版本使用 - 1.7.0.45

在我現有的servlet代碼,我一直在處理通過使用NIO後簡單的請求。但是現在如果一個客戶端已經設置了傳輸編碼分塊,我需要專門處理它。所以我有一個分叉代碼。類似下面,

inputStream = httpServletRequest.getInputStream(); 

if ("chunked".equals(getRequestHeader(httpServletRequest, "Transfer-Encoding"))) { 
    // Need to process chunked data 
} else { 
    // normal request data 
    if (inputStream != null) { 
    int contentLength = httpServletRequest.getContentLength() 
    if (contentLength <= 0) { 
     return new byte[0]; 
    } 
    ReadableByteChannel channel = Channels.newChannel(inputStream); 
    byte[] postData = new byte[contentLength]; 
    ByteBuffer buf = ByteBuffer.allocateDirect(contentLength); 
    int numRead = 0; 
    int counter = 0; 
    while (numRead >= 0) { 
     buf.rewind(); 
     numRead = channel.read(buf); 
     buf.rewind(); 
     for (int i = 0; i < numRead; i++) { 
      postData[counter++] = buf.get(); 
     } 
    } 
    return postData; 
    } 
} 

所以,如果你注意觀察,正常情況下請求是基於「內容長度」可用,而對於分塊編碼,即不存在。因此是處理分塊數據的另一個過程。

感謝,

玉萍

+1

爲什麼你堅持對'java.io'代碼頂部分層NIO代碼?這樣做沒有任何效率:相反。只需使用流。你確定你必須做任何事情嗎?我希望HttpServletRequest能夠處理分塊。 – EJP

回答

0

HTTP 1/1 Chunked Transfer Coding

您的servlet將以大小可變的塊提供服務。你會得到它的第一行每個塊的大小。協議很簡單,所以你可以自己實現它。

+0

我知道格式和目的。就這一點而言,我在尋找是否有任何開箱即用的東西,就像我最初的搜索拋出ChunkedInputStream或ChunkedInputFilter作爲參考。此外,我想使用NIO API來做到這一點,因爲我使用AsyncContext。 – Vicky

+0

Apache的'ChunkedInputStream'似乎是一個完美的選擇。你試過了嗎? –

+0

不,我還沒有嘗試過。只是想從人們瞭解什麼是最好的方式來做到這一點。如果有更好的選擇。像ChunkedInputFilter是我已經使用的tomcat的一部分,但我還沒有找到很多關於它的文檔。 – Vicky

-1

下列基於NIO代碼爲我工作,

ReadableByteChannel channel = Channels.newChannel(chunkedInputStream); 

    // content length is not known upfront, hence a initial size 
    int bufferLength = 2048; 

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength); 

    int numRead = 0; 
    while (numRead >= 0) { 
     byteBuffer.rewind(); 
     //Read bytes from the channel 
     numRead = channel.read(byteBuffer); 
     byteBuffer.rewind(); 

     if (numRead > 0) { 
      byte[] dataBytes = byteBuffer.array(); 
      baos.write(dataBytes, 0, dataBytes.length); 
     } 

     byteBuffer.clear(); 
    } 

    return baos.toByteArray(); 
+3

我沒有看到任何與此代碼中分析分塊數據相關的內容。 – Vadzim