python+request使用方法简单介绍

python+request使用方法简单介绍安装 request 库 pipinstallre 导入库 importreques 构建各种 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

安装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

(0)
上一篇 2026年3月19日 下午6:50
下一篇 2026年3月19日 下午6:51


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号