如何通过JMeter自动批量发送4000个JSON格式POST请求?
自动化批量发送4000条JSON POST请求的方案
方法一:JMeter 配置元件实现批量请求(无需手动创建线程组)
- 预处理JSON文件:把原文件改成每行一个完整JSON对象的格式(如果原本是逗号分隔的数组,用简单脚本拆分即可),示例:
{"u_id": "00", "u_operation": "Address", "u_service": "Fiber", "u_characteristic": 2, "u_name": "Address #1"} {"u_id": "01", "u_operation": "Address", "u_service": "TV", "u_characteristic": 2, "u_name": "Address #2"} - 添加CSV数据设置器:
在单个线程组下添加「CSV Data Set Config」元件,设置:- 「Filename」:你的JSON文件路径
- 「Variable Names」:自定义变量名(比如
json_payload) - 「Delimiter」:留空(因为每行是完整JSON)
- 「Recycle on EOF」:设为
False - 「Stop thread on EOF」:设为
True
- 配置HTTP请求:
添加「HTTP Request」元件,请求方法选POST,填写API地址;在「Body Data」中直接引用变量:${json_payload}。 - 调整并发与循环:
线程组的「Number of Threads (users)」根据API承受能力设置(比如10、20,不用设4000),「Loop Count」设为4000,或勾选「Forever」配合CSV的停止规则自动结束。若之前超时,可在HTTP请求的「Advanced」里调大超时时间,或添加「Constant Timer」控制请求间隔,避免压垮API。
方法二:Python脚本批量发送(灵活可控)
用Python脚本读取JSON文件,批量发送请求,支持重试、并发控制:
import json import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from concurrent.futures import ThreadPoolExecutor # 配置会话与重试策略 session = requests.Session() retry = Retry(connect=3, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) session.mount('http://', adapter) session.mount('https://', adapter) API_URL = "你的API地址" JSON_FILE = "你的JSON文件路径" # 读取JSON数据(支持数组格式或每行一个JSON对象) with open(JSON_FILE, 'r', encoding='utf-8') as f: # 若为数组格式,用payloads = json.load(f) payloads = [json.loads(line.strip()) for line in f if line.strip()] # 单条请求发送逻辑 def send_request(payload, idx): try: response = session.post(API_URL, json=payload, timeout=10) response.raise_for_status() print(f"第{idx}条请求发送成功,状态码:{response.status_code}") except Exception as e: print(f"第{idx}条请求失败:{str(e)}") # 控制并发数执行(比如20个线程) with ThreadPoolExecutor(max_workers=20) as executor: for idx, payload in enumerate(payloads, 1): executor.submit(send_request, payload, idx)
- 优势:可自定义并发数、请求间隔,失败自动重试,还能扩展日志记录、结果统计等功能。
关键注意事项
- 不要一次性发起4000个并发请求,容易触发API限流或本地网络超时,根据API性能文档调整并发数。
- 先测试10条以内的请求,确认JSON格式、API响应正常后再批量执行。
- 若API需要认证,在HTTP请求或Python脚本中添加对应的请求头(比如
Authorization)。
内容的提问来源于stack exchange,提问作者tr6
相关产品推荐
相关产品推荐

