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=utf8
import httplib
httpClient
= None
try
:
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 e
finally
:
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=utf8
import httplib, urllib
httpClient
= None
try
:
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 e
finally
:
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