Python http学习
1、python发送GET请求
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 5 import httplib 6 7 httpClient = None 8 9 try: 10 httpClient = httplib.HTTPConnection('localhost', 80, timeout=30) 11 httpClient.request('GET', '/test.php') 12 13 # response是HTTPResponse对象 14 response = httpClient.getresponse() 15 print response.status 16 print response.reason 17 print response.read() 18 except Exception, e: 19 print e 20 finally: 21 if httpClient: 22 httpClient.close()
2、python发送POST请求
1 #!/usr/bin/python 2 # -*- coding: UTF-8 -*- 3 4 5 import httplib, urllib 6 7 httpClient = None 8 try: 9 params = urllib.urlencode({'name': 'tom', 'age': 22}) 10 headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} 11 12 httpClient = httplib.HTTPConnection("localhost", 80, timeout=30) 13 httpClient.request("POST", "/test.php", params, headers) 14 15 response = httpClient.getresponse() 16 print response.status 17 print response.reason 18 print response.read() 19 print response.getheaders() # 获取头信息 20 except Exception, e: 21 print e 22 finally: 23 if httpClient: 24 httpClient.close()