In Python, analog HTTP clients send get and post requests, primarily with the functionality of the Httplib module.
1. Python sends a GET request
I built a test environment locally, the test.php content is to output a sentence:
| 1 |
echo‘Old friends and old wines are best.‘; |
Python sends a GET request code:
| 123456789101112131415161718192021 |
#!/usr/bin/env python#coding=utf8import httplibhttpClient = Nonetry: httpClient = httplib.HTTPConnection(‘localhost‘, 80, timeout=30) httpClient.request(‘GET‘, ‘/test.php‘) #response是HTTPResponse对象 response = httpClient.getresponse() print response.status print response.reason print response.read()except Exception, e: print efinally: if httpClient: httpClient.close() |
Finally is used in the above code to ensure that httpclient can be closed even when an error occurs. Run this program and output the results on my computer as follows:
Python sends a GET request with Httplib
2. Python sends a POST request
Modify the test.php content to print out the $_post array:
Python initiates the POST request code:
| 123456789101112131415161718192021222324 |
#!/usr/bin/env python#coding=utf8import httplib, urllibhttpClient = Nonetry: params = urllib.urlencode({‘name‘: ‘tom‘, ‘age‘: 22}) headers = {"Content-type": "application/x-www-form-urlencoded" , "Accept": "text/plain"} httpClient = httplib.HTTPConnection("localhost", 80, timeout=30) httpClient.request("POST", "/test.php", params, headers) response = httpClient.getresponse() print response.status print response.reason print response.read() print response.getheaders() #获取头信息except Exception, e: print efinally: if httpClient: httpClient.close() |
Run the code and output the following on my computer:
Python sends a POST request with Httplib
Python sends get and POST requests with the Httplib module