在Linux环境下,有多种工具可以用来测试HTTP的GET和POST请求。以下是几种常用的方法:
curl http://example.com/api/resource
curl "http://example.com/api/resource?param1=value1¶m2=value2"
curl -X POST http://example.com/api/resource \
-H "Content-Type: application/json" \
-d '{"key1":"value1", "key2":"value2"}'
-v
:显示详细输出(verbose)-H
:添加请求头-d
:发送POST数据-X
:指定HTTP方法-o
:将输出保存到文件-u
:基本认证(username:password)wget http://example.com/api/resource
wget --post-data="param1=value1¶m2=value2" \
--header="Content-Type: application/x-www-form-urlencoded" \
http://example.com/api/resource
telnet example.com 80
GET / HTTP/1.1
Host: example.com
[按两次回车]
printf "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | nc example.com 80
首先安装:
sudo apt install httpie # Debian/Ubuntu
sudo yum install httpie # CentOS/RHEL
http GET http://example.com/api/resource
http POST http://example.com/api/resource key1=value1 key2=value2
如果你已经创建了Postman集合,可以使用newman在命令行运行测试:
newman run mycollection.json
import requests
# GET请求
response = requests.get('http://example.com/api/resource')
print(response.text)
# POST请求
response = requests.post('http://example.com/api/resource',
json={'key': 'value'})
print(response.json())
结合curl和jq可以很好地处理JSON响应:
curl -s http://example.com/api/resource | jq '.'
# 获取用户列表
curl -X GET http://api.example.com/users
# 创建新用户
curl -X POST http://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name":"John Doe","email":"john@example.com"}'
# 带认证的请求
curl -u username:password http://api.example.com/protected-resource
curl -X POST http://example.com/upload \
-H "Content-Type: multipart/form-data" \
-F "file=@/path/to/file.txt"
选择哪种工具取决于你的具体需求和个人偏好。对于简单的测试,curl通常是最快捷的选择;对于更复杂的场景,可能需要使用专门的API测试工具或编写脚本。