为什么 HTTP 响应没有给我指定的数据范围?

Why is the HTTP response not giving me my specified range of data?

因此,我使用范围 属性 从 url 抓取一个 HTTP 对象,例如 .png。我找到整个对象的内容长度,然后拆分每个范围的起始字节和结束字节。一切正常,直到最后一个范围。

// My specified range is:
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Range", "bytes=22128-27657");

// It returns (Response Header):
HTTP/1.1 206 Partial Content
Thu, 17 Mar 2016 17:04:34 GMT
Downloaded Size: 5533
bytes
5529
bytes 22128-27656/27657 // !!! - Incorrect
Keep-Alive

但是,在其他所有范围内,我都得到了我要求的数据:

// My specified range is:
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Range", "bytes=5533-11066");

// It returns (Response Header):
HTTP/1.1 206 Partial Content
Thu, 17 Mar 2016 17:04:34 GMT
Downloaded Size: 5533
bytes
5529
bytes 5533-11066/27657 // !!! - Correct
Keep-Alive

发生了什么事?

Content-Range header 的值定义为(缩写):

 Content-Range       = byte-content-range
 byte-content-range  = bytes-unit SP byte-range-resp
 byte-range-resp     = byte-range "/" ( complete-length / "*" )
 byte-range          = first-byte-pos "-" last-byte-pos
 complete-length     = 1*DIGIT

section 2.1说:

 first-byte-pos      = 1*DIGIT
 last-byte-pos       = 1*DIGIT

The first-byte-pos value in a byte-range-spec gives the byte-offset of the first byte in a range. The last-byte-pos value gives the byte-offset of the last byte in the range; that is, the byte positions specified are inclusive. Byte offsets start at zero.

因此长度为 27657,位置为 0-27656

当您请求 22128-27657 时,您请求的字节数超过了可用字节数,并且响应被截断为实际可用字节数。

字节范围是从 0 开始索引的。对于 bytes=22128-27657,您要求从第 22129 个字节到第 27658 个字节,但只有 27657 个字节。你的两个例子都表现正确。