调用接口 (get,post,传cookie,入参json)

 1 # import urllib #python自带  发网络请求的一个模块 [不好用]
 2 
 3 from urllib.request import urlopen
 4 from urllib.parse import urlencode
 5 import json
 6 url = 'http://api.nnzhp.cn/api/user/stu_info'
 7 d = {'stu_name':'矿泉水'}
 8 req = urlopen(url,urlencode(d).encode()) #指定路径和参数
 9 #必须要先用urlencode把字典转换成字符串,然后还要继续转成二进制
10 
11 print(req.read().decode())#返回的是字符串
12 result = json.loads(req.read().decode()) #转换成字典的形式
13 print(result)
14 
15 #以上 不好用 仅限于 知道就ok
16 
17 import requests
18 
19 #get请求
20 url = 'http://api.nnzhp.cn/api/user/stu_info'
21 d = {'stu_name':'矿泉水'}
22 req = requests.get(url,d)
23 print(req.json())#返回的是字典
24 print(req.text) #返回的是字符串
25 
26 #post请求
27 url = 'http://api.nnzhp.cn/api/user/login'
28 data = {'username':'niuhanyang','passwd':'aA123456'}
29 req = requests.post(url,data)
30 print(req.json())
31 
32 #传cookie的方式
33 url = 'http://api.nnzhp.cn/api/user/gold_add'
34 data = {'stu_id': 6307,'gold':99}
35 cookie = {'niuhanyang':'d0378b2def134d736ae358121cf38ff0'}
36 req = requests.post(url,data,cookies=cookie)
37 print(req.text)
38 
39 url = 'http://api.nnzhp.cn/api/user/gold_add'
40 data = {'stu_id': 6307,'gold':99}
41 cookie = {'niuhanyang':'d0378b2def134d736ae358121cf38ff0'}
42 cookie2 = {'cookie':'niuhanyang=d0378b2def134d736ae358121cf38ff0'}
43 # req = requests.post(url,data,cookies=cookie)
44 req = requests.post(url,data,headers=cookie2)#用headers的方法
45 print(req.text)
46 
47 #用第二种headers的方式比较方便,因为cookie值有很多个的时候,用haeders直接复制就可以了
48 #但是用key->value的方式的话 要一个key一个value的写进去 比价麻烦
49 
50 #入参是json的
51 data = {
52     "name": "矿泉水222",
53     "sex": "未知",
54     "age": 38,
55     "addr": "天通苑",
56     "grade": "双子座",
57     "phone": "15901211115",
58     "gold": 100
59 }
60 
61 url = 'http://api.nnzhp.cn/api/user/add_stu'
62 req = requests.post(url,json=data)
63 print(req.text)
64 
65 #上传文件
66 url = 'http://api.nnzhp.cn/api/file/file_upload'
67 data = {'file':open('上传文件用','rb')}#b代表二进制
68 req = requests.post(url,files = data)
69 print(req.text)
70 
71 #下载 图片/音乐  [网络传输都是用二进制进行传输的]
72 url = 'http://aliuwmp3.changba.com/userdata/userwork/12107482.mp3'
73 req = requests.get(url) #只要能在浏览器里直接打开的都是get请求
74 with open('aqmm.mp3','wb') as fw:
75     print(req.content) #content  代表返回二进制的内容
76   fw.write(req.content) #返回的文件要存起来,返回的内容写入文件
77 
78 url = 'https://aliimg.changba.com/cache/photo/18189396_640_640.jpg'
79 req = requests.get(url) #只要能在浏览器里直接打开的都是get请求
80 with open('aqmm.jpg','wb') as fw:
81     print(req.content) #content  代表返回二进制的内容
82   fw.write(req.content) #返回的文件要存起来,返回的内容写入文件
原文地址:https://www.cnblogs.com/baiby/p/10968618.html