在各种大模型的API文档中,经常会用到 curl 工具,那么——如何运行 curl 脚本呢?

在Linux平台
对于复杂的代码,建议创建脚本文件:
# 创建脚本文件
nano myscript.sh
然后执行以下指令
# 在文件中粘贴代码,然后保存退出
chmod +x myscript.sh # 添加执行权限
./myscript.sh # 执行脚本
在Windows 平台
首先编写脚本文件(前提:已经下载安装好 windows 版本的 curl),假设文件名为 curl-exe-script.ps1(注意尾缀为ps1)
# curl-exe-script.ps1
Write-Host "=== 使用真正的 cURL 工具 ===" -ForegroundColor Yellow# ————————————————————以下均为示例——————————————————————
# 实例1:基本 GET 请求
curl.exe -s "https://httpbin.org/json"# 实例2:下载文件
curl.exe -o "downloaded-file.jpg" "https://httpbin.org/image/jpeg"
Write-Host "文件下载完成"# 实例3:带 Header 的请求
curl.exe -H "User-Agent: My-Script" -H "Accept: application/json" "https://httpbin.org/headers"# 实例4:POST 请求 with JSON
curl.exe -X POST "https://httpbin.org/post" `-H "Content-Type: application/json" `-d '{"name": "John", "email": "john@example.com"}' `-s
执行前的准备工作:
默认情况下,PowerShell 的执行策略可能限制脚本运行。因此需要执行以下命令
# 检查当前执行策略
Get-ExecutionPolicy# 设置执行策略以允许脚本运行(需要管理员权限)
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser# 或者临时绕过(仅当前会话)
Set-ExecutionPolicy -ExecutionPolicy Bypass -Scope Process
执行脚本
powershell
# 方法1: 直接执行
.\curl-script.ps1# 方法2: 使用 PowerShell 命令
powershell -File .\curl-script.ps1# 方法3: 带参数执行
powershell -ExecutionPolicy Bypass -File .\curl-script.ps1