python 使用 requests 做 http 请求
1. get
import requests # 最简单的get请求 r = requests.get(url) print(r.status_code) print(r.json()) # url 中?key=value&key=value r = requests.get(url, params=params) # form 表单 params = {"username":"name", "password":"passw0rd"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = requests.get(url, params=params, headers=headers) # 下载 r = requests.get(url) r.raise_for_status() with open(target, 'wb') as f: for ch in r.iter_content(10000): result_file_size += f.write(ch)
2. post请求
data = {'name':'train', 'device':'CN0989'} r = requests.post(url, json=data) #上传 files = { "file": (os.path.basename(filepath), open(filepath, "rb"), "application/zip") } print('POST %s'%url) with open(filepath, 'rb') as f: r = requests.post(url, files=files)
r = requests.post(url, json=json_dict, headers=headers) # 保持response流,保证接收完整 with requests.get('https://httpbin.org/get', stream=True) as r: # Do things with the response here. # 上传文件 with open('massive-body', 'rb') as f: requests.post('http://some.url/streamed', data=f) # 上传文件 2 指定文件格式 files = {'file': (filename, open(filename, 'rb), 'application/zip')} r = requests.post(url, files=files) print(r.status_code) print(r.json()) # 上传多个文件 url = 'https://httpbin.org/post' multiple_files = [ ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')), ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))] r = requests.post(url, files=multiple_files) r.text
# 防止中文乱码 url = 'http://hostname' body = {'name':'中文名称'} print('body:\n%s' % json.dumps(body, ensure_ascii=False)) body = json.dumps(body, ensure_ascii=False) body = body.encode('utf-8') r = _session.post(url, data=body, headers={'Content-Type': 'application/json;charset=UTF-8'}) status_code = r.status_code res = r.json()
3. 登录
_session = requests.Session() # login url = '%s/login'%_basic_url params = {"username":"admin", "password":"admin"} headers = {'Content-Type':'application/x-www-form-urlencoded'} r = _session.post(url, params=params, headers=headers) #做其他请求 r = _session.get(url) _session.close()
4. 使用basic登录
也可以如上方一样使用session
from requests.auth import HTTPBasicAuth r = requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass')) r.encoding = 'utf-8' print r.status_code print r.text print r.json()