In python, simulate the http client to send get and post requests, mainly using the functions of the httplib module.
1. Python sends a GET request
I set up a test environment locally, and the content of python.php is to output a sentence:
1 |
<?php |
2 |
echo 'python httplib study!' .PHP_EOL; |
3 |
var_dump( $_POST ); |
4 |
?> |
python send get request code:
01 |
#!/usr/bin/env python |
02 |
# -*- coding: gbk -*- |
03 |
# -*- coding: utf-8 -*- |
04 |
# Date: 2014/8/19 |
05 |
# Created by 独自等待 |
06 |
# 博客 http://www.waitalone.cn/ |
07 |
import httplib |
08 |
09 |
httpClient = None |
10 |
11 |
try : |
12 |
httpClient = httplib.HTTPConnection( 'localhost' , 80 , timeout = 10 ) |
13 |
httpClient.request( 'GET' , '/python.php' ) |
14 |
15 |
# response是HTTPResponse对象 |
16 |
response = httpClient.getresponse() |
17 |
print response.status |
18 |
print response.reason |
19 |
print response.read() |
20 |
except Exception, e: |
21 |
print e |
22 |
finally : |
23 |
if httpClient: |
24 |
httpClient.close() |
Finally is used in the above code to ensure that httpClient can be closed even if there is an error. Running this program produces the following output on my computer:
2. Python sends a POST request
Modify the content of python.php and print out the $_POST array:
1 |
<?php |
2 |
echo 'python httplib study!' .PHP_EOL; |
3 |
var_dump( $_POST ); |
4 |
?> |
Python initiates post request code:
01 |
#!/usr/bin/env python |
02 |
# -*- coding: gbk -*- |
03 |
# -*- coding: utf-8 -*- |
04 |
# Date: 2014/8/19 |
05 |
# Created by 独自等待 |
06 |
# 博客 http://www.waitalone.cn/ |
07 |
import urllib, httplib |
08 |
09 |
httpClient = None |
10 |
try : |
11 |
params = urllib.urlencode({ 'name' : 'waitalone.cn' , 'age' : '5' }) |
12 |
headers = { 'Content-type' : 'application/x-www-form-urlencoded' , 'Accept' : 'text/plain' } |
13 |
httpClient = httplib.HTTPConnection( 'localhost' , 80 , timeout = 10 ) |
14 |
httpClient.request( 'POST' , '/python.php' , params, headers) |
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() |