一个简单的http发送请求代码学习

Signed-off-by: shuiyu1123 <f17376088816@163.com>
This commit is contained in:
shuiyu1123 authored and Gitee committed 2025-02-27 11:24:31 +00:00
1 parent 47263050f1
commit 1bb951cc3d
1 file changed
+53
+53
View File
@@ -0,0 +1,53 @@
import requests
import concurrent.futures
import time
import logging
# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def send_request(ip, port=80, path='/', interval=1, count=10):
"""
向指定IP地址发送HTTP请求
:param ip: 目标IP地址
:param port: 目标端口,默认为80
:param path: 请求路径,默认为'/'
:param interval: 请求间隔时间(秒),默认为1秒
:param count: 发送请求的次数,默认为10次
"""
url = f"http://{ip}:{port}{path}"
for i in range(count):
try:
response = requests.get(url, timeout=5) # 设置超时时间
logging.info(f"Request {i+1}: Status Code = {response.status_code}")
except requests.exceptions.RequestException as e:
logging.error(f"Request {i+1} failed: {e}")
time.sleep(interval)
def main():
# 询问用户输入IP地址
target_ip = input("请输入目标IP地址: ")
# 询问用户输入端口(可选)
target_port = input("请输入目标端口(默认80): ")
target_port = int(target_port) if target_port.isdigit() else 80
# 询问用户输入请求路径(可选)
target_path = input("请输入请求路径(默认'/'): ")
target_path = target_path if target_path else '/'
# 询问用户输入请求间隔时间(可选)
request_interval = input("请输入请求间隔时间(秒,默认1秒): ")
request_interval = float(request_interval) if request_interval.replace('.', '', 1).isdigit() else 1
# 询问用户输入发送请求的次数(可选)
request_count = input("请输入发送请求的次数(默认10次): ")
request_count = int(request_count) if request_count.isdigit() else 10
# 询问用户输入线程数(可选)
thread_count = input("请输入线程数(默认5): ")
thread_count = int(thread_count) if thread_count.isdigit() else 5
# 创建线程池并发送请求
with concurrent.futures.ThreadPoolExecutor(max_workers=thread_count) as executor:
for _ in range(thread_count):
executor.submit(send_request, target_ip, target_port, target_path, request_interval, request_count)
if __name__ == '__main__':
main()