从服务器读取带偏移的文件
我想从服务器上读取一个文件,但希望从某个特定的位置开始(就像wget -c那样)。我需要向服务器发送什么请求头?服务器需要支持哪些功能?
2 个回答
在 http://www.gnu.org/software/wget/manual/wget.html 上
注意,‘-c’这个选项只适用于ftp服务器和支持Range头的http服务器。
在 https://www.rfc-editor.org/rfc/rfc2616 上
这里有一些字节范围的示例值(假设实体的长度为
10000):- The first 500 bytes (byte offsets 0-499, inclusive): bytes=0- 499 - The second 500 bytes (byte offsets 500-999, inclusive): bytes=500-999 - The final 500 bytes (byte offsets 9500-9999, inclusive): bytes=-500 - Or bytes=9500- - The first and last bytes only (bytes 0 and 9999): bytes=0-0,-1 - Several legal but not canonical specifications of the second
500字节(字节偏移量500-999,包括500和999):
bytes=500-600,601-999
bytes=500-700,601-999
所以你应该发送
Range:bytes=9500-
要测试一个服务器是否支持这个功能,你可以这样测试accept-range。
接受字节范围请求的源服务器可能会发送
Accept-Ranges: bytes
但并不是必须这样做。客户端可以在没有收到这个头信息的情况下,生成字节范围请求。范围单位在第3.12节中定义。
不接受任何类型范围请求的服务器可能会发送
Accept-Ranges: none
来提醒客户端不要尝试进行范围请求。
你应该在请求中使用 Range
这个头信息。不过,只有当服务器告诉你它支持范围请求时,你才能使用它,这个信息是通过 Accept-Ranges
这个响应头来传达的。
下面是一个示例过程。假设我们想获取 这张图片 的一部分。首先,我们发送一个 HTTP HEAD
请求来确定:a) 服务器是否支持字节范围,b) 内容的长度:
> HEAD /2238/2758537173_670161cac7_b.jpg HTTP/1.1
> Host: farm3.static.flickr.com
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Thu, 08 Jul 2010 12:22:12 GMT
< Content-Type: image/jpeg
< Connection: keep-alive
< Server: Apache/2.0.52 (Red Hat)
< Expires: Mon, 28 Jul 2014 23:30:00 GMT
< Last-Modified: Wed, 13 Aug 2008 06:13:54 GMT
< Accept-Ranges: bytes
< Content-Length: 350015
接下来,我们发送一个 GET
请求,并在请求中加入 Range
头,要求获取这张图片的前 11 个字节:
> GET /2238/2758537173_670161cac7_b.jpg HTTP/1.1
> Host: farm3.static.flickr.com
> Accept: */*
> Range: bytes=0-10
>
< HTTP/1.1 206 Partial Content
< Date: Thu, 08 Jul 2010 12:26:54 GMT
< Content-Type: image/jpeg
< Connection: keep-alive
< Server: Apache/2.0.52 (Red Hat)
< Expires: Mon, 28 Jul 2014 23:30:00 GMT
< Last-Modified: Wed, 13 Aug 2008 06:13:54 GMT
< Accept-Ranges: bytes
< Content-Range: bytes 0-10/350015
< Content-Length: 11
<
这是前 11 个字节的十六进制转储:
00000000 ff d8 ff e0 00 10 4a 46 49 46 00 |......JFIF.|
0000000b
想了解更多信息,可以查看 HTTP RFC 2616 中的 Range 头信息规范。