Python-GET/POST请求(urllib.request与requests)使用Python测试POST接口(代替postman)

本文介绍了使用Python的urllib及requests库调用HTTP接口的方法。涵盖了GET与POST请求的发送,展示了如何处理请求头与参数,并从JSON文件中加载数据进行发送。

接口基本信息

接口地址:http://127.0.0.1:8080/testpro/api/common/service
调用方式:POST
参数:JSON格式字符串,放到独立的.json文件中
返回:调用码返回200且,返回内容有效,则验证成功

代码示例

使用urllib.request调用接口

urlopen()只能用于一些简单的资源请求

# 爬百度数据
from urllib import request

response = request.urlopen("http://www.baidu.com")
fi = open("my_baidu.txt","w")
page = fi.write(str(response.read()))
fi.close()//必须要关闭资源

#处理get请求,不传data,则为get请求
import urllib
from urllib.request import urlopen
from urllib.parse import urlencode

url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
req_data=urlencode(data)#将字典类型的请求数据转变为url编码
res=urlopen(url+'?'+req_data)#通过urlopen方法访问拼接好的url
res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str

print(res)

#处理post请求,如果传了data,则为post请求
import urllib
from urllib.request import Request
from urllib.parse import urlencode

url='http://www.xxx.com/login'
data={"username":"admin","password":123456}
data=urlencode(data)#将字典类型的请求数据转变为url编码
data=data.encode('ascii')#将url编码类型的请求数据转变为bytes类型
req_data=Request(url,data)#将url和请求数据处理为一个Request对象,供urlopen调用
with urlopen(req_data) as res:
    res=res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str
print(res)

示例二 :

import urllib
from urllib.request import urlopen
from urllib.request import Request
from urllib.parse import urlencode
import json 

url='http://127.0.0.1:8080/testpro/api/common/service'
#使用 with as 打开文件,不用自己单独关闭资源
with open("myFirstPythonPrj/requestDataTxt.json","r",encoding='utf-8') as f:
    print(f.read())#执行完read后,指针跑到了 文件最后,故后边json.load(f)会报错
    print("现在文件对象位置:%d" % f.tell())     # 返回文件对象当前位置
    f.seek(0,0)    # 移动文件对象至第一个字符

    dict_data = json.load(f)
    print(dict_data)

    data = urlencode(dict_data)#将字典类型的请求数据转变为url编码
    data = data.encode('ascii')#将url编码类型的请求数据转变为bytes类型
    headers = {'content-type': 'application/json'}
   req_data = Request(url,data, headers=headers)#将url和请求数据处理为一个Request对象,供urlopen调用

    res = Request.post(url,data, headers=headers)
    print(res)
    with urlopen(req_data) as res:
    res = res.read().decode()#read()方法是读取返回数据内容,decode是转换返回数据的bytes格式为str

    print(res)

使用requests实现接口调用

requests是对urllib的进一步封装,在使用上更加的方便。
需要提前安装requests模块,使用命令:pip install requests

import json 
import requests

url='http://127.0.0.1:8080/testpro/api/common/service'

#使用 with as 打开文件,不用自己单独关闭资源
with open("myFirstPythonPrj/requestDataTxt.json","r",encoding='utf-8') as f:
    header={
        "Content-Type":"application/json"
    }
    datas = json.load(f)
    get_res = requests.get(url,headers=headers,params=None)
    # post_res = requests.post(url,headers=headers,data=None,json=None)
    post_res = requests.post(url, json=datas,headers=header)
    print("状态码:"+ str( r.status_code ) ) #打印状态码
    print(post_res.text)

get_res.text得到的是str数据类型。
get_res.content得到的是Bytes类型,需要进行解码。作用和get_response.text类似。
get_res.json得到的是json数据。

# -*- coding: utf-8 -*- """ ============================ requests 课件:HTTP 请求核心方法详解 ============================ 版本:3.1 | 修复 JSON 解码错误 + 最佳实践示例 📌 使用的免费测试接口: 1. https://jsonplaceholder.typicode.com/ - 提供标准 REST API 接口 2. https://postman-echo.com/post - 稳定的 POST 测试接口,支持表单提交 """ # 🧠 What:requests 是什么? # requestsPython 中最常用的 HTTP 客户端库,用于向 Web 服务器发送各种类型的请求。 # 它广泛应用于 API 调试、接口测试、网络爬虫等场景。 # 🛠 How:怎么使用? # - 使用 requests.get() 发送 GET 请求 # - 使用 requests.post() 发送 POST 请求 # - 使用 requests.put() 发送 PUT 请求 # - 使用 requests.delete() 发送 DELETE 请求 # - 使用 params、data、json 控制请求体 # - 使用 headers 设置请求头 # - 使用 timeout 控制超时时间 # - 使用异常处理保障程序健壮性 # 🎯 Why:为什么要用 requests? # - 简洁易用,语法直观 # - 支持多种 HTTP 方法 # - 自动处理编码和解码 # - 社区活跃,文档丰富 # - 适用于自动化脚本、接口测试、爬虫等 import requests # ==================== # 第一部分:GET 请求详解 # ==================== # 示例 1:最基础的 GET 请求 def demo_get_simple(): """最基础的 GET 请求示例""" print("=== 示例 1:最基础的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts/1" response = requests.get(url) print(f"状态码: {response.status_code}") print("响应内容(前50字符):") print(response.text[:50] + "...") # 示例 2:带查询参数的 GET 请求 def demo_get_with_params(): """带查询参数的 GET 请求示例""" print("=== 示例 2:带查询参数的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts" params = { "userId": 1, "_limit": 2 } response = requests.get(url, params=params) print(f"完整URL: {response.url}") print("返回数据:") for item in response.json(): print(f"ID: {item['id']}, 标题: {item['title']}") # 示例 3:带请求头的 GET 请求 def demo_get_with_headers(): """带请求头的 GET 请求示例""" print("=== 示例 3:带请求头的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts" headers = { "User-Agent": "MyApp/1.0", "Accept": "application/json" } response = requests.get(url, headers=headers) print(f"响应头 Content-Type: {response.headers['Content-Type']}") print("第一条数据标题:", response.json()[0]['title']) # 示例 4:带超时和异常处理的 GET 请求 def demo_get_with_timeout(): """带超时和异常处理的 GET 请求示例""" print("=== 示例 4:带超时和异常处理的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts" try: response = requests.get(url, timeout=3) response.raise_for_status() print("请求成功,返回数据条数:", len(response.json())) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # ==================== # 第二部分:POST 请求详解 # ==================== # 示例 5:最基础的 POST 请求JSON 数据) def demo_post_simple_json(): """最基础的 POST 请求JSON 数据)""" print("=== 示例 5:最基础的 POST 请求JSON 数据) ===") url = "https://jsonplaceholder.typicode.com/posts" data = { "title": "新文章", "body": "这是内容", "userId": 1 } response = requests.post(url, json=data) print(f"状态码: {response.status_code}") print("返回数据 ID:", response.json()['id']) # 示例 6:POST 发送表单数据(使用支持 form 数据返回的接口) def demo_post_form_data(): """POST 发送表单数据示例(使用 httpd.js.org)""" print("=== 示例 6:POST 发送表单数据 ===") url = "https://httpd.js.org/posts" data = { "username": "testuser", "password": "testpass" } response = requests.post(url, data=data) print("服务器收到的数据:") try: result = response.json() print("form 数据:", result.get('form', '未找到 form 数据')) except requests.exceptions.JSONDecodeError: print("响应内容不是有效的 JSON!原始内容:") print(response.text) # 示例 7:POST 发送 JSON + 自定义 Headers def demo_post_json_with_headers(): """POST 发送 JSON + 自定义 Headers 示例""" print("=== 示例 7:POST 发送 JSON + 自定义 Headers ===") url = "https://jsonplaceholder.typicode.com/posts" data = { "title": "高级文章", "body": "带自定义头", "userId": 1 } headers = { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest" } response = requests.post(url, json=data, headers=headers) print("返回标题:", response.json()['title']) # 示例 8:POST 发送 JSON + 超时和异常处理 def demo_post_with_timeout(): """POST 发送 JSON + 超时和异常处理示例""" print("=== 示例 8:POST 发送 JSON + 超时和异常处理 ===") url = "https://jsonplaceholder.typicode.com/posts" data = { "title": "测试超时", "body": "超时测试内容", "userId": 1 } try: response = requests.post(url, json=data, timeout=3) response.raise_for_status() print("创建成功,ID:", response.json()['id']) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.RequestException as e: print(f"请求失败: {e}") # ==================== # 第三部分:PUT 请求详解 # ==================== # 示例 9:使用 PUT 更新资源 def demo_put_update(): """使用 PUT 请求更新资源示例""" print("=== 示例 9:使用 PUT 请求更新资源 ===") url = "https://jsonplaceholder.typicode.com/posts/1" data = { "id": 1, "title": "更新后的标题", "body": "更新后的内容", "userId": 1 } response = requests.put(url, json=data) print(f"状态码: {response.status_code}") print("更新后的标题:", response.json()['title']) # ==================== # 第四部分:DELETE 请求详解 # ==================== # 示例 10:使用 DELETE 删除资源 def demo_delete_resource(): """使用 DELETE 请求删除资源示例""" print("=== 示例 10:使用 DELETE 请求删除资源 ===") url = "https://jsonplaceholder.typicode.com/posts/1" response = requests.delete(url) print(f"状态码: {response.status_code}") print("响应内容:", response.text) # ==================== # 第五部分:综合实战(最佳实践示例) # ==================== # 示例 11:最佳实践 - 完整请求流程(headers + timeout + session + 异常处理) def demo_best_practice(): """最佳实践示例:完整请求流程 + 安全调用""" print("=== 示例 11:最佳实践 - 完整请求流程 ===") url = "https://jsonplaceholder.typicode.com/posts" headers = { "User-Agent": "BestPracticeApp/1.0", "Accept": "application/json" } data = { "title": "最佳实践文章", "body": "这是一篇测试文章", "userId": 1 } with requests.Session() as session: session.headers.update(headers) try: response = session.post(url, json=data, timeout=5) response.raise_for_status() print("文章创建成功,ID:", response.json()['id']) except requests.exceptions.Timeout: print("请求超时,请检查网络") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求异常: {e}") # ==================== # 主函数:运行所有示例 # ==================== if __name__ == "__main__": print("🚀 开始演示 requests 核心请求方法详解") demo_get_simple() demo_get_with_params() demo_get_with_headers() demo_get_with_timeout() demo_post_simple_json() demo_post_form_data() demo_post_json_with_headers() demo_post_with_timeout() demo_put_update() demo_delete_resource() demo_best_practice() # 最佳实践 print("\n✅ 所有演示完成") 打印出的结果不是所有接口都能用,你需要保证所有接口都可以正常调用,不然没办法给学生讲/Users/10280281/PycharmProjects/PythonProject/.venv/bin/python /Users/10280281/PycharmProjects/PythonProject/.venv/lib/python3.9/python_course/module2_functions/lesson_requests.py /Users/10280281/PycharmProjects/PythonProject/.venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020 warnings.warn( 🚀 开始演示 requests 核心请求方法详解 === 示例 1:最基础的 GET 请求 === 状态码: 200 响应内容(前50字符): { "userId": 1, "id": 1, "title": "sunt aut f... === 示例 2:带查询参数的 GET 请求 === 完整URL: https://jsonplaceholder.typicode.com/posts?userId=1&_limit=2 返回数据: ID: 1, 标题: sunt aut facere repellat provident occaecati excepturi optio reprehenderit ID: 2, 标题: qui est esse === 示例 3:带请求头的 GET 请求 === 响应头 Content-Type: application/json; charset=utf-8 第一条数据标题: sunt aut facere repellat provident occaecati excepturi optio reprehenderit === 示例 4:带超时和异常处理的 GET 请求 === 请求成功,返回数据条数: 100 === 示例 5:最基础的 POST 请求JSON 数据) === 状态码: 201 返回数据 ID: 101 === 示例 6:POST 发送表单数据 === 服务器收到的数据: 响应内容不是有效的 JSON!原始内容: <!doctype html> <html> <head> <meta charset="utf-8"> <title>302 httpd - JS.ORG</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#FFE70B"> <link rel="icon" type="image/png" href="https://js.org/ico/favicon-32.png"> <link rel="icon" type="image/svg+xml" href="https://js.org/ico/favicon.svg"> <style> html, body { height: 100%; margin: 0; background: #FFE70B; } iframe { width: 100%; height: 100%; border: 0; } </style> </head> <body> <iframe src="https://js.org/302?httpd.js" sandbox="allow-same-origin allow-scripts allow-top-navigation"></iframe> </body> </html> === 示例 7:POST 发送 JSON + 自定义 Headers === 返回标题: 高级文章 === 示例 8:POST 发送 JSON + 超时和异常处理 === 创建成功,ID: 101 === 示例 9:使用 PUT 请求更新资源 === 状态码: 200 更新后的标题: 更新后的标题 === 示例 10:使用 DELETE 请求删除资源 === 状态码: 200 响应内容: {} === 示例 11:最佳实践 - 完整请求流程 === 文章创建成功,ID: 101 ✅ 所有演示完成 进程已结束,退出代码为 0
最新发布
09-05
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值