安装request库
pip install requests
导入库
import requests
构建各种http请求
get请求
requests.get('https://api.github.com/events')
post请求
requests.post('http://httpbin.org/post', data = {'key':'value'})
put请求
requests.put('http://httpbin.org/put', data = {'key':'value'})
delete请求
requests.delete('http://httpbin.org/delete')
构建URL参数
get请求
payload = {'key1': 'value1', 'key2': 'value2'} requests.get("http://httpbin.org/get", params=payload)
构建请求头
h1={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36', } requests.get('http://localhost/api/mgr/sq_mgr/', headers=h1, params=payload)
payload={'action':'add_course', 'data':'''{ "name":"初中化学", "desc":"初中化学课程", "display_idx":"4" }''' } resp=requests.post("http://localhost/api/mgr/sq_mgr/", data=payload)
请求体类型:Content-Type: application/json
可以将字典直接传递给json参数
payload2={ "action" : "add_course_json", "data" : { "name":"初中化学", "desc":"初中化学课程", "display_idx":"4" } } resp=requests.post("http://localhost/apijson/mgr/sq_mgr/", json=payload2)
注意参数和URL的区别!!!!
查看响应内容
先获取到响应对象response
resp=requests.post("http://localhost/api/mgr/sq_mgr/", data=payload)
拿到响应对象就可以查看服务器返回的各种消息内容了
# 查看响应体: resp.text #查看响应头: resp.headers #如果响应体恰巧是json格式: resp.json() #自动把json格式的字符串转成python对象,通常都是字典类型 #那么再获取字典里面具体的值就很好操作了 retObj=resp.json() if retObj['retcode'] == 0: print('pass') else: print(retObj['retcode'])
request官方文档网址
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/205085.html原文链接:https://javaforall.net
