怎么用脚本发送网络请求

wen 实用脚本 2

本文目录导读:

怎么用脚本发送网络请求

  1. Python 脚本
  2. curl 命令(Shell)
  3. Node.js 脚本
  4. Bash 脚本
  5. 高级用法示例
  6. 选择建议

Python 脚本

使用 requests 库(最常用)

import requests
# GET 请求
response = requests.get('https://api.example.com/data')
print(response.status_code)
print(response.json())
# POST 请求
data = {'key': 'value'}
response = requests.post('https://api.example.com/post', json=data)
# 带请求头
headers = {
    'Authorization': 'Bearer token123',
    'Content-Type': 'application/json'
}
response = requests.get('https://api.example.com/secure', headers=headers)
# 带参数
params = {'page': 1, 'limit': 10}
response = requests.get('https://api.example.com/list', params=params)
# 处理超时
try:
    response = requests.get('https://api.example.com', timeout=5)
except requests.Timeout:
    print('请求超时')

使用 urllib(标准库)

import urllib.request
import json
# GET 请求
url = 'https://api.example.com/data'
response = urllib.request.urlopen(url)
data = json.loads(response.read())
# POST 请求
data = json.dumps({'key': 'value'}).encode('utf-8')
req = urllib.request.Request(
    url, 
    data=data, 
    headers={'Content-Type': 'application/json'}
)
response = urllib.request.urlopen(req)

curl 命令(Shell)

# GET 请求
curl https://api.example.com/data
# POST 请求
curl -X POST -H "Content-Type: application/json" \
     -d '{"key":"value"}' \
     https://api.example.com/post
# 带认证
curl -u username:password https://api.example.com/secure
# 带 Bearer token
curl -H "Authorization: Bearer token123" https://api.example.com/secure
# 下载文件
curl -o file.txt https://example.com/file.txt

Node.js 脚本

使用 axios

const axios = require('axios');
// GET 请求
async function getData() {
    try {
        const response = await axios.get('https://api.example.com/data');
        console.log(response.data);
    } catch (error) {
        console.error('请求失败:', error.message);
    }
}
// POST 请求
async function postData() {
    const data = { key: 'value' };
    try {
        const response = await axios.post('https://api.example.com/post', data);
        console.log(response.data);
    } catch (error) {
        console.error('请求失败:', error.message);
    }
}
// 带配置
const config = {
    headers: { Authorization: 'Bearer token123' },
    timeout: 5000
};

使用原生 fetch(Node.js 18+)

// GET 请求
async function getData() {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
}
// POST 请求
async function postData() {
    const response = await fetch('https://api.example.com/post', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ key: 'value' })
    });
    const data = await response.json();
    console.log(data);
}

Bash 脚本

#!/bin/bash
# GET 请求
API_URL="https://api.example.com/data"
response=$(curl -s "$API_URL")
echo "$response"
# POST 请求
curl -s -X POST \
  -H "Content-Type: application/json" \
  -d '{"key":"value"}' \
  "https://api.example.com/post"
# 带重试机制
for i in {1..3}; do
    response=$(curl -s --retry 3 "$API_URL")
    if [ $? -eq 0 ]; then
        break
    fi
    sleep 2
done

高级用法示例

并发请求(Python)

import asyncio
import aiohttp
async def fetch_all(urls):
    async with aiohttp.ClientSession() as session:
        tasks = []
        for url in urls:
            tasks.append(session.get(url))
        responses = await asyncio.gather(*tasks)
        return responses
# 使用
urls = ['https://api1.com', 'https://api2.com']
responses = asyncio.run(fetch_all(urls))

模拟浏览器行为

import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    'Accept': 'text/html,application/xhtml+xml',
    'Accept-Language': 'zh-CN,zh;q=0.9',
}
# 会话持久化(保持 Cookie)
session = requests.Session()
session.headers.update(headers)
# 先登录
login_data = {'username': 'user', 'password': 'pass'}
session.post('https://example.com/login', data=login_data)
# 然后请求需要认证的页面
response = session.get('https://example.com/dashboard')

选择建议

  • 简单测试:使用 curl 命令
  • 复杂逻辑:Python requests 库
  • 异步处理:Node.js 或 Python asyncio
  • 前端测试:Node.js fetch 或 axios
  • 系统脚本:Bash + curl

记得处理异常、超时和验证响应状态码哦!

抱歉,评论功能暂时关闭!