网络编程,主要是引入urllib模块中的urlopen用法和urlencode用法
from urllib.request import urlopen
from urllib.parse import urlencode
import requests
1)get请求
url = 'http://118.24.3.40/api/user/stu_info'
方法一:
res = urlopen(url) #发送get请求
print(res.read().decode())
方法二:
res = request.get(url,params = {'stu_name':'小黑'}) #发送get请求
print(res.json()) #直接把返回结果转成字典
2)post请求
url2 = 'http://118.24.3.40/api/user/login'
方法一:
data = {'username':'niuhanyang','passwd':'123456'}
res = urlopen(url2,urlencode(data).encode()) #发送post请求
print(res.read().decode())
方法二:
data = {'username':'niuhanyang','passwd':'123456'}
res = request.post(url2,data = data)
print(res.json)
3)入参是json格式的
url3 = 'http://118.24.3.40/api/user/add_stu'
data = {"name":"wwww","grade":"spz","phone","15500000000","sex":"男","age":"18","addr":"北京市朝阳区"}
res = request.post(url3,json = data)
print(res.json())
4)cookie类型
url4 = 'http://118.24.3.40/api/user/gold_add'
data = {'stu_id':15,'gold':200}
cookie = {'niuhanyang':'xxxxxxxx'}
res = request.post(url4,data = data,cookies = cookie)
print(res.json)
5)header格式
url5 = 'http://118.24.3.40/api/user/all_stu'
header = {'Referer':'http://api.nnzhp.cn/'}
res = request.get(url5,headers = header)
print(res.json())
6)下载文件
url6 = 'http://qiniuuwmp3.changba.com/234234.mp3'
res = request.get(url6,verify = False) #如果请求接口是https的,需要加上verify = False
print(res.text)
print(res.content) #返回的就是二进制
with open('aaa.mpe','wb') as fw:
fw.write(res.content)
print(res.cookie) #获取到返回的所有cookie
print(res.headers) #获取到所有返回的header
7)上传图片
url7 = 'http://118.24.3.40/api/file/file_upload'
data = {'file':open('D:\pic\aaa.jpeg','rb')}
res = request.post(url7,files = data)
print(res.json)