import httplib
def httpCode(theurl):
if theurl.startswith("http://"): theurl = theurl[7:]
head = theurl[:theurl.find('/')]
tail = theurl[theurl.find('/'):]
response_code = 0
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
response_code = int(res.status)
return response_code
Обычно эта функция берет URL-адрес и возвращает его HTTP-код (200, 404 и т. Д.)
Я получил ошибку:
Exception Value: (-2, 'Name or service not known')
Я должен сделать это с помощью этого метода. То есть я обычно передаю большие видео файлы. Мне нужно получить «заголовок» и получить код HTTP. Я не могу загрузить файл и затем получить код HTTP, потому что это займет слишком много времени.
Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import httplib
>>> def httpCode(theurl):
... if theurl.startswith("http://"): theurl = theurl[7:]
... head = theurl[:theurl.find('/')]
... tail = theurl[theurl.find('/'):]
... response_code = 0
... conn = httplib.HTTPConnection(head)
... conn.request("HEAD",tail)
... res = conn.getresponse()
... response_code = int(res.status)
... print response_code
...
>>> httpCode('http://youtube.com')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in httpCode
File "/usr/lib/python2.6/httplib.py", line 874, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py", line 911, in _send_request
self.endheaders()
File "/usr/lib/python2.6/httplib.py", line 868, in endheaders
self._send_output()
File "/usr/lib/python2.6/httplib.py", line 740, in _send_output
self.send(msg)
File "/usr/lib/python2.6/httplib.py", line 699, in send
self.connect()
File "/usr/lib/python2.6/httplib.py", line 683, in connect
self.timeout)
File "/usr/lib/python2.6/socket.py", line 498, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known
>>>