如果传输编码被分块,如何使用java获取http响应中的块大小 [英] how to get the size of chunk in http response using java if transfer encoding is chunked

查看:1061
本文介绍了如果传输编码被分块,如何使用java获取http响应中的块大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果传输编码被分块,如何知道HTTP响应块的大小。我无法获得逻辑。
请帮帮我。并提供一些示例java代码来获取chunk的大小。我在一些书中读到每个块的大小是在块本身之前指定的。但是使用哪个逻辑我可以得到它。
请帮我使用java。

How to know the size of the chunk of HTTP response if transfer encoding is chunked.I am unable to get the logic. Please help me.And provide me some sample java code to get the size of chunk.I read in some books that size of each chunk is specified before the chunk itself.But using which logic can I get that. Please help me using java.

谢谢。

推荐答案

无法准备好使用代码,但Apache HttpClient库支持开箱即用的一切。

Not able to give ready to use code but Apache HttpClient library supports "everything" out of the box.

这是chikied响应的维基百科示例。在读取正文部分之前,您不知道数据的确切字节大小。请注意每个块的大小是十六进制值,最后0大小的块是数据的结尾。它也被2字节的CRLF分隔符终止。

This is wikipedia example of chunked response. You don't know the exact byte size of data until body part is read. Please note size of each chunk is hexadecimal value, last 0 sized chunk is end of data. It too is terminated by 2-byte CRLF delimiter.

Transfer-Encoding: chunked\r\n
Content-Type: text/plain\r\n
\r\n
4\r\n
Wiki\r\n
5;extkey=extvalue\r\n
pedia\r\n
E\r\n
.in\r\n
\r\n
chunks.\r\n
0\r\n
AfterBodyHeader: some value\r\n
AfterBodyHeader2: any value\r\n
\r\n




  • 读取字节直到CRLF(\\\\ n或0D0A为十六进制)

  • 删除所有内容;分隔符或停止在尾随CRLF,一些回复可能会在块大小的行添加扩展名。忽略它们,除非你等待已知的键值对。

  • 将十六进制转换为整数,它告诉你块中的数据字节数

  • 读取x字节数并附加到ByteArrayOutputBuffer

  • 读取尾随CRLF分隔符字节并忽略它

  • 如果不是0大小再次读取大小+块数据

  • 一些响应可能会添加 AfterHeaders 它们就像响应开始时的标题

  • 在0大小的块后面是一个空行(\ r \ n)表示完整的http响应结束。如果没有 AfterHeaders ,最后应该看到字节0 \\\\\\\ n。请注意,常规块可能包含空行,因此在0大小的指示符之前不要终止解析。

    • read bytes until CRLF (\r\n or 0D0A in hex)
    • drop everything after ; delimiter or stop at trailing CRLF, some replys may add extensions at the line of chunk size. Ignore them unless you wait for known key-value pair.
    • convert hex to integer, it tells you num of data bytes in chunk
    • read x num of bytes and append to ByteArrayOutputBuffer
    • read trailing CRLF delimiter bytes and ignore it
    • if not 0 sized read again size+chunk data
    • some responses may add AfterHeaders they are like headers at the start of response
    • after 0 sized chunk an empty line (\r\n) indicates end of complete http response. If there is no AfterHeaders you should see bytes 0\r\n\r\n in the end. Please note regular chunks may contain empty lines so do not terminate parsing until 0-sized indicator.
    • 此示例使用\\\ n个占位符表示2字节分隔符,因为规格要求

      This example uses \r\n placeholders to indicate 2-byte delimiter as specs require

      这篇关于如果传输编码被分块,如何使用java获取http响应中的块大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆