原文地址
这个话题是从实现一个http资源的静态访问引发的。http协议从1.1开始支持获取文件的部分内容,这为并行下载以及断点续传提供了技术支持。它通过在Header里两个参数实现的,客户端发请求时对应的是Range,服务器端响应时对应的是Content-Range;通过tomcat看一下这两个参数。
在应用的根目录下放了一张图片”chain.jpg”,图片的大小是4932字节,用curl模拟分段请求,请求时把respons的header给dump到一个文件里:
$ curl -D "resp-header1.txt" -H 'Range: bytes=0-2000' \
http://localhost:8080/chain.jpg > /tmp/test.jpg
$ cat resp-header1.txt
HTTP/1.1 206 Partial Content # 返回状态码是206
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"4932-1447753566000"
Last-Modified: Tue, 17 Nov 2015 09:46:06 GMT
Content-Range: bytes 0-2000/4932
Content-Type: image/jpeg
Content-Length: 2001
Date: Tue, 17 Nov 2015 17:27:45 GMT
这时在mac下用preview程序打开图片看到是部分的,把剩余部分数据也下载下来才行:
$ curl -H 'Range: bytes=2001-4932' \
http://localhost:8080/chain.jpg >> /tmp/test.jpg
Range参数还支持多个区间,用逗号分隔,下面对另一个内容为”hello world”的文件”a.html”多区间请求,这时response的Content-Type不再是原文件mime类型,而用一种multipart/byteranges类型表示:
$ curl -D 'resp-header' -H 'Range: bytes=0-5,6-10' http://localhost:8080/a.html
--CATALINA_MIME_BOUNDARY
Content-Type: text/html
Content-Range: bytes 0-5/12
hello
--CATALINA_MIME_BOUNDARY
Content-Type: text/html
Content-Range: bytes 6-10/12
world
--CATALINA_MIME_BOUNDARY--
$ cat resp-header
HTTP/1.1 206 Partial Content
Server: Apache-Coyote/1.1
Accept-Ranges: bytes
ETag: W/"12-1447780011000"
Last-Modified: Tue, 17 Nov 2015 17:06:51 GMT
Content-Type: multipart/byteranges; boundary=CATALINA_MIME_BOUNDARY
Content-Length: 208
Date: Tue, 17 Nov 2015 17:39:30 GMT
本文探讨了HTTP协议中Range请求头的使用方式及其响应Content-Range的行为。通过具体示例展示了如何利用Range请求实现文件的分段下载,并介绍了多区间请求的特点。
1万+

被折叠的 条评论
为什么被折叠?



