前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python通过httplib发送GET和POST请求代码

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

原创
作者头像
用户7365393
修改2021-11-02 11:22:10
1.1K0
修改2021-11-02 11:22:10
举报

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()</pre> 

 发送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()</pre> 

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档