Python发送GET和POST请求

雨点打透心脏的1/2处 2022-08-25 08:38 324阅读 0赞

在python中,模拟http客户端发送get和post请求,主要用httplib模块的功能。

1、python发送GET请求

我在本地建立一个测试环境,test.php的内容就是输出一句话:

[php] view plain copy

  1. echo ‘Old friends and old wines are best.’;

python发送get请求代码:

[python] view plain copy

  1. #!/usr/bin/env python
  2. #coding=utf8
  3. import httplib
  4. httpClient = None
  5. try:
  6. httpClient = httplib.HTTPConnection(‘localhost’, 80, timeout=30)
  7. httpClient.request(‘GET’, ‘/test.php’)
  8. #response是HTTPResponse对象
  9. response = httpClient.getresponse()
  10. print response.status
  11. print response.reason
  12. print response.read()
  13. except Exception, e:
  14. print e
  15. finally:
  16. if httpClient:
  17. httpClient.close()

上面代码中使用了finally来保证即使出错的时候也能关闭httpClient。

2、python发送POST请求
修改test.php内容,打印出$_POST数组:

[php] view plain copy

  1. var_dump($_POST);

python发起post请求代码:

[python] view plain copy

  1. #!/usr/bin/env python
  2. #coding=utf8
  3. import httplib, urllib
  4. httpClient = None
  5. try:
  6. params = urllib.urlencode({ ‘name’: ‘tom’, ‘age’: 22})
  7. headers = { “Content-type”: “application/x-www-form-urlencoded”
  8. , “Accept”: “text/plain”}
  9. httpClient = httplib.HTTPConnection(“localhost”, 80, timeout=30)
  10. httpClient.request(“POST”, “/test.php”, params, headers)
  11. response = httpClient.getresponse()
  12. print response.status
  13. print response.reason
  14. print response.read()
  15. print response.getheaders() #获取头信息
  16. except Exception, e:
  17. print e
  18. finally:
  19. if httpClient:
  20. httpClient.close()

发表评论

表情:
评论列表 (有 0 条评论,324人围观)

还没有评论,来说两句吧...

相关阅读