为什么在python中会出现这个错误?(httplib)

2024-04-26 07:08:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有人知道什么是“坏状态线”吗?

编辑:我在很多服务器上都试过了,但是很多URL仍然会出现这个错误?


Tags: inpyhttpresponselibusrstatusline
3条回答

Python标准库:httplib (Python 2)(称为http.client in Python 3):

exception httplib.BadStatusLine
A subclass of HTTPException. Raised if a server responds with a HTTP status code that we don’t understand.

我最近遇到了这个错误,在这种情况下,包含http请求的方法成功运行了一次,然后在第二次调用该方法(使用不同的URL)时抛出了这个异常(状态代码为空字符串)。我有一个调试优势,因为这是调用我自己的REST api,所以我在服务器端做了一些日志记录,发现从未收到请求。我最终发现我的URL字符串有一个尾随的换行符。因此,请确保您的url中没有任何前导或尾随的特殊字符。

httplib (Python 2)(称为http.client in Python 3)的文档中:

exceptionhttplib.BadStatusLine: (exceptionhttp.client.BadStatusLine:)

A subclass of HTTPException.

Raised if a server responds with an HTTP status code that we don’t understand.

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

>>> 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)

我想只要再检查一遍再试试?

相关问题 更多 >