urllib模块去请求的确比较麻烦,需要不断的encode和decode;而requests模块就比较方便了,它是基于requests模块开发的第三方模块,安装简单只需要 pip install requests即可。
import requests
url= 'http://127.0.0.1:8080/login'
data = {"username":"cws1235","pwd":123456}
#######get请求
req = requests.get(url,data).json() 返回的是json字典类型,接口返回必须是json才可以
req= requests.get(url,data).text 返回的是字符串
def post_jsonpppp(self): #处理post返回json的请求
还可以拼接请求:
req = requests.get(url+'username=cws12356&pwd=123456')
########post请求
req = requests.post(url,data)
#如果入参是json
data2 = {
"username":'jmy1235',
"real_name":"处长",
"class":"巨蟹座",
"phone":"19312345673",
}
requests.post(url,json=data2).text #发送请求报文是json
##那如果是url里有参数,body里面还有json请求
eg.1
http://127.0.0.1:8080/login?username=niuhanyang&pwd=123456 然后body里还有json
方法有两种:1、拼接 2、在传入一个参数
req=requests.post(url,data2,json=data2)
req=requests.get(url+''?''+"username=hubing&pwd=123456",data2)
####带cookie的
url = "http://127.0.0.1:8000/add_stu2"
data = {"userid":1}
cookie = {"token":"token12345"}
res = requests.post(url,data,cookies=cookie,json=data2).json()#使用cookies参数执行cookie
####添加验证权限的
url="http://127.0.0.1:8000/add_stu2"
data ={'userid':1,"money":9999}
res =requests.post(url,data,auth=('admin','123456')).json()
####带header的
hearder={"tavnxiaofei":"7wei"}
url = "http://127.0.0.1:8000/add_stu2"
res = requests.post(url,json=data2,cookies=cookie,headers=header) .json() #用headers参数,header里面不能有中文
####发送文件
url = "http://127.0.0.1:8000/add_stu2"
s = requests.session()
req_param = '{"belongId": "312","userName": "testss003","password":"pxkj88","captcha":"pxpx","captchaKey":"59675w1v8kdbpxv"}'
res = s.post('http://test.e.fanxiaojian.cn/metis-login-web/auth/login', json=json.loads(req_param))
print(res.json())
print(res.cookies.values())
text的不管返回是不是json都可以