为什么在Python中会出现httplib.BadStatusLine?

28 投票
11 回答
73077 浏览
提问于 2025-04-15 16:11
if theurl.startswith("http://"): theurl = theurl[7:]
    head = theurl[:theurl.find('/')]
    tail = theurl[theurl.find('/'):]
response_code = 0
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
response_code = int(res.status)

http://www.garageband.com/mp3cat/.UZCKbS6N4qk/01_Saraenglish.mp3
Traceback (most recent call last):
  File "check_data_404.py", line 51, in <module>
    run()
  File "check_data_404.py", line 35, in run
    res = conn.getresponse()
  File "/usr/lib/python2.6/httplib.py", line 950, in getresponse
    response.begin()
  File "/usr/lib/python2.6/httplib.py", line 390, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.6/httplib.py", line 354, in _read_status
    raise BadStatusLine(line)
httplib.BadStatusLine

有没有人知道什么是“坏状态行”?

补充一下:我试了很多服务器和很多网址,还是遇到这个错误?

11 个回答

9

Python标准库中的内容:httplib(Python 2)(在Python 3中叫做http.client):

exception httplib.BadStatusLine
这是HTTPException的一个子类。如果服务器返回一个我们不理解的HTTP状态码,就会引发这个异常。

28

我最近遇到了一个错误。在第一次调用包含HTTP请求的方法时,它运行得很成功,但第二次调用这个方法(使用不同的URL)时却抛出了一个异常,状态码是空字符串。我有一个调试的优势,因为这是在调用我自己的REST API,所以我在服务器端做了一些日志记录,发现请求根本没有被接收到。最后我发现我的URL字符串后面多了一个换行符。所以一定要确保你的URL没有多余的特殊字符,比如前后的空格或换行符。

32

根据httplib(Python 2)的文档(在Python 3中叫http.client):

异常 httplib.BadStatusLine: (异常 http.client.BadStatusLine:)

这是HTTPException的一个子类。

当服务器返回一个我们无法理解的HTTP状态码时,就会抛出这个异常。

我运行了相同的代码,但没有收到错误:

>>> theurl = 'http://www.garageband.com/mp3cat/.UZCKbS6N4qk/01_Saraenglish.mp3'
>>> if theurl.startswith("http://"):
...     theurl = theurl[7:]
...     head = theurl[:theurl.find('/')]
...     tail = theurl[theurl.find('/'):]
... 
>>> head
'www.garageband.com'
>>> tail
'/mp3cat/.UZCKbS6N4qk/01_Saraenglish.mp3'
>>> response_code = 0
>>> import httplib
>>> conn = httplib.HTTPConnection(head)
>>> conn.request("HEAD", tail)
>>> res = conn.getresponse()
>>> res.status
302
>>> response_code = int(res.status)

我想再检查一遍所有内容,然后再试一次?

撰写回答