在python中,模擬http客戶端發送get和post請求,主要用httplib模塊的功能。
1、python發送GET請求
我在本地建立一個測試環境,test.php的內容就是輸出一句話:
1
|
echo
'Old friends and old wines are best.'
;
|
python發送get請求代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#!/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來保證即使出錯的時候也能關閉httpClient。運行這個程序,在我的電腦上輸出結果如下:
2、python發送POST請求
修改test.php內容,打印出$_POST數組:
1
|
var_dump(
$_POST
);
|
python發起post請求代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
#!/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()
|
運行代碼,在我的電腦上輸出如下: