为什么我使用 httplib 时会出现 socket.gaierror?

为什么我使用 httplib 时会出现 socket.gaierror?

我的程序的目的是向登录页面发送 POST 请求,但是我收到以下错误。

#!/usr/bin/env python      
import httplib,urllib       
conn = httplib.HTTPConnection("localhost")   
conn.request("GET", "/xampp/mantisbt-1.2.2/login_page.php")  
r1 = conn.getresponse()  
print r1.status, r1.reason   
data1 = r1.read()  
params = urllib.urlencode({'Username': 'administrator', 'Password': 'password'})  
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/html"}  
conn = httplib.HTTPConnection("localhost/xampp/mantisbt-1.2.2/login.php")    
conn.request("POST","localhost/xampp/mantisbt-1.2.2/login.php",params, headers)  
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()

输出:

200 OK
Traceback (most recent call last):   
  File "./client_postnew.py", line 11, in <module>   
    conn.request("POST","localhost/xampp/mantisbt-1.2.2/login.php",params, headers)  
  File "/usr/lib/python2.6/httplib.py", line 910, in request      
    self._send_request(method, url, body, headers)      
  File "/usr/lib/python2.6/httplib.py", line 947, in _send_request   
    self.endheaders()    
  File "/usr/lib/python2.6/httplib.py", line 904, in endheaders    
    self._send_output()
  File "/usr/lib/python2.6/httplib.py", line 776, in _send_output     
    self.send(msg)
  File "/usr/lib/python2.6/httplib.py", line 735, in send
    self.connect()
  File "/usr/lib/python2.6/httplib.py", line 716, in connect          
    self.timeout)   
  File "/usr/lib/python2.6/socket.py", line 500, in create_connection    
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):   
socket.gaierror: [Errno -2] Name or service not known

答案1

脚本的第 10 行和第 11 行:

conn = httplib.HTTPConnection("localhost/xampp/mantisbt-1.2.2/login.php")
conn.request("POST","localhost/xampp/mantisbt-1.2.2/login.php",params, headers)

您正在创建一个HTTP连接带有错误参数的对象:查看文档,签名为:

class httplib.HTTPConnection(host[, port[, strict[, timeout[, source_address]]]])

HTTP连接获取主机名,HTTPConnection.请求()采用路径。因此你应该这样写:

conn = httplib.HTTPConnection("localhost")
conn.request("POST","localhost/xampp/mantisbt-1.2.2/login.php",params, headers)

相关内容