python通过httplib发送GET和POST请求代码

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

python有一个httplib的库,提供了很方便的方法实现GET和POST请求,只需要简单的组织一下即可。

python发送get请求代码:
#!/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()

发送POST请求
#!/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()

标签: 代码

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇: js时间格式化

下一篇:iOS 自定义瀑布流相册控件