Curl | 原创,AI翻译
这是一个结合了多个 curl 示例的 bash 脚本:
#!/bin/bash
# 基础 GET 请求
echo "基础 GET 请求:"
curl http://example.com
# 带自定义请求头的 GET 请求
echo "\n带自定义请求头的 GET 请求:"
curl -H "User-Agent: MyUserAgent/1.0" http://example.com
# POST 请求
echo "\nPOST 请求:"
curl -X POST -d "key1=value1&key2=value2" http://example.com/post
# 带 JSON 数据的 POST 请求
echo "\n带 JSON 数据的 POST 请求:"
curl -X POST -H "Content-Type: application/json" -d "{\"key1\":\"value1\",\"key2\":\"value2\"}" http://example.com/post
# 使用代理
echo "\n使用代理:"
curl -x http://proxy.example.com:8080 http://example.com
# 身份验证
echo "\n基础身份验证:"
curl -u username:password http://example.com/auth
# 下载文件
echo "\n下载文件:"
curl -O http://example.com/file.zip
# 跟随重定向
echo "\n跟随重定向:"
curl -L http://example.com/redirect
# 将输出保存到文件
echo "\n将输出保存到文件:"
curl http://example.com -o output.txt
# 自定义 HTTP 方法
echo "\n自定义 HTTP 方法(DELETE):"
curl -X DELETE http://example.com/delete/resource
# 详细输出
echo "\n详细输出:"
curl -v http://example.com
# 连接超时
echo "\n连接超时:"
curl --connect-timeout 5 http://example.com
echo "\n脚本执行完成。"
将此脚本保存为 .sh 扩展名文件,例如 curl_examples.sh。如果在类 Unix 环境或 Windows 子系统 Linux (WSL) 中运行,请确保将其设置为可执行文件:
chmod +x curl_examples.sh
然后,您可以运行它:
./curl_examples.sh
Windows 注意事项:
- 如果在 Windows Cmd 或 PowerShell 中运行此脚本,需要安装 WSL 并使用
bash或wsl命令,或者确保curl在您的 PATH 环境变量中以便直接执行:bash curl_examples.sh或wsl ./curl_examples.sh
- 请注意,此脚本使用 bash 语法,除非通过 WSL 或 bash 环境运行,否则无法在 Windows 命令提示符或 PowerShell 中本地兼容。不过,
curl命令本身与 Windows 版本的curl兼容。