用urllib2断点下载

问题

Lerry [email protected]
发件人当地时间 发送时间 21:47 (GMT+08:00)。发送地当前时间:下午6:06。 ✆
日期      2011年7月25日 下午9:47
主题      [CPyUG]请问如何使用urllib2断点下载

我想使用urllib2断点下载文件,网上说是在header里面定义Content-Range 我的代码如下

   1 Python code
   2 import urllib2 as l
   3 a = l.Request('http://127.0.0.1/123.txt')
   4 a.add_header('Content-Range:','bytes 5-8/9')
   5 f = l.urlopen(a)
   6 print f.read()

但是不起作用,请问是为什么

解决

Zhao Xiaohong [email protected] 通过“googlegroups.com”
发件人当地时间 发送时间 22:46 (GMT-07:00)。发送地当前时间:上午3:05。 ✆
日期      2011年7月26日 下午10:46
主题      [CPyUG] Re: 请问如何使用urllib2断点下载

看来你成功了. 不过我既然我也弄了, 我还是贴一下:

首先验证 web server 支持断点续传:

(django13)[www@mail ~]$ curl -i http://127.0.0.1/123.txt
HTTP/1.1 200 OK
Server: nginx/0.8.54
Date: Tue, 26 Jul 2011 14:41:53 GMT
Content-Type: text/plain
Content-Length: 10
Last-Modified: Tue, 26 Jul 2011 14:32:35 GMT
Connection: keep-alive
Accept-Ranges: bytes

123456789

然后安装 rfc2616 传送对应的 header:

(django13)[www@mail ~]$ python
Python 2.7.1 (r271:86832, May 19 2011, 13:05:13)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-50)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import httplib2
>>> h = httplib2.Http()
>>> h.request('http://127.0.0.1/123.txt', headers={'Range': 'bytes=0-4'})
({'status': '206', 'content-length': '5', 'content-range': 'bytes
0-4/10', 'server': 'nginx/0.8.54', 'last-modified': 'Tue, 26 Jul 2011
14:32:35 GMT', 'connection': 'keep-alive', 'date': 'Tue, 26 Jul 2011
14:43:19 GMT', 'content-type': 'text/plain'}, '12345')

>>> h.request('http://127.0.0.1/123.txt', headers={'Range': 'bytes=4-'})
({'status': '206', 'content-length': '6', 'content-range': 'bytes
4-9/10', 'server': 'nginx/0.8.54', 'last-modified': 'Tue, 26 Jul 2011
14:32:35 GMT', 'connection': 'keep-alive', 'date': 'Tue, 26 Jul 2011
14:43:38 GMT', 'content-type': 'text/plain'}, '56789\n')


反馈

创建 by -- ZoomQuiet [2011-07-27 10:09:34]

MiscItems/2011-07-27 (last edited 2011-07-27 10:09:32 by ZoomQuiet)