python中你用什么库发送HTTP请求呢,urllib,urllib2? 下面介绍一个更简单的:requests。 使用requests,可以简洁高效的发送HTTP请求。
###直接使用pip安装
$ pip install requests
如果没有安装pip,首先
$ easy_install pip
安装成功,得到提示:
Installing collected packages: requests Successfully installed requests-2.14.2 …
###使用源码安装: 获取源码
$ git clone git://github.com/kennethreitz/requests.git
进入源码根目录,执行如下命令进行安装:
$ python setup.py install
使用方法
r = requests.get(....)
返回结果在r中,例如r.content 返回内容,r.status_code返回状态码。
###2.1不带参数
#!/usr/bin/python
import requests
url="http://my.os/notification/charm/"
r = requests.get(url)
print r.status_code
print r.content
####2.2带参数
#!/usr/bin/python
import requests
url="http://my.os/notification/charm/"
payload={'message': "Opportunities and challenges together"}
r = requests.get(url, params=payload)
print r.status_code
print r.content
###2.3定制请求头
例如,添加认证信息
#!/usr/bin/python
import requests
url="http://my.os/notification/charm/"
headers={'Authorization': 'token 52ee7d4c57686ca8d6884fa4c482a28'}
payload={'message': "Opportunities and challenges together"}
r = requests.get(url, headers=headers, params=payload)
print r.status_code
print r.content
备注: 关于token认证格式,不同应用的格式可能略有不同,需要根据实际服务端的要求调整。 例如,下面3中格式:
Authorization’: ‘token 52ee7d4c57686ca8d6884fa4c482a28’ Authorization’: ‘access_token 52ee7d4c57686ca8d6884fa4c482a28’ Authorization’: ‘52ee7d4c57686ca8d6884fa4c482a28’
使用方法
r = requests.post(...)
r中包含结果r.content, 状态码r.status_code
###简单请求
#!/usr/bin/python
import requests
url="http://my.os/api/notification/charm/"
payload={'message': "Opportunities and challenges together"}
r = requests.post(url, data=payload)
print r.status_code
print r.content
###定制请求头
例如,添加认证信息
#!/usr/bin/python
import requests
url="http://my.os/api/notification/charm/"
headers={'Authorization': 'token 52ee7d4c57686ca8d6884fa4c482a28'}
payload={'message': "Opportunities and challenges together"}
r = requests.post(url, headers=headers, data=payload)
print r.status_code
print r.content
http://docs.python-requests.org/zh_CN/latest/user/quickstart.html