2014-01-09 47 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