Python 3中的http.client请求方法

时间:2014-07-10 08:17:33

标签: python-3.x

当我运行此代码时:

import http.client
hR = ["/index.html"]
conn = http.client.HTTPConnection("www.python.org", 80)
conn.connect()
conn.request("GET", hR)
response = conn.getresponse()
data = response.read()
print (data)
conn.close()

我收到以下错误:

Traceback (most recent call last):
  File "C:\Python32\files\fcon.py", line 5, in <module>
    conn.request("GET", hR)
  File "C:\Python32\lib\http\client.py", line 964, in request
    self._send_request(method, url, body, headers)
  File "C:\Python32\lib\http\client.py", line 992, in _send_request
    self.putrequest(method, url, **skips)
  File "C:\Python32\lib\http\client.py", line 877, in putrequest
    if url.startswith('http'):
AttributeError: 'list' object has no attribute 'startswith'

此外,当我将第3行中的网址更改为“http://python.org”时,我收到了其他错误:

Traceback (most recent call last):
  File "C:\Python32\files\fcon.py", line 4, in <module>
    conn.connect()
  File "C:\Python32\lib\http\client.py", line 721, in connect
    self.timeout, self.source_address)
  File "C:\Python32\lib\socket.py", line 380, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11001] getaddrinfo failed

1 个答案:

答案 0 :(得分:3)

第一条错误消息告诉您hR不应该是列表,而应该是字符串,这样可行:

import http.client
hR = "/index.html"
conn = http.client.HTTPConnection("www.python.org", 80)
conn.connect()
conn.request("GET", hR)
response = conn.getresponse()
data = response.read()
print (data)
conn.close()

但是,您不会看到任何数据,因为python.org只会回复一个http 301,并会重定向到其https页面,而http.client 自动跟随。

您收到的第二个错误是因为http://www.python.org不是有效的主机名,www.python.org在这里是正确的。

http.client是一个相当低级别的API,您应该考虑使用urllib.request,或者甚至考虑使用requests库。