curl是Linux下测试HTTP接口的核心工具,支持GET、POST、认证、自定义Header、超时控制及文件上传等全场景用法。

如果您需要在Linux系统中向远程服务器发送HTTP请求以测试接口功能,curl命令是最常用且功能强大的工具之一。以下是多种使用curl发送不同类型HTTP请求的具体方法:
一、发送GET请求
GET请求用于从服务器获取资源,是测试接口最基本的方式。curl默认即为GET方法,无需额外指定。
1、在终端中输入curl后跟目标URL,例如:curl https://httpbin.org/get。
2、如需显示响应头信息,添加 -I 参数:curl -I https://httpbin.org/get。
3、若需保存响应内容到文件,使用 -o 参数:curl -o response.json https://httpbin.org/get。
二、发送POST请求并携带JSON数据
POST请求常用于向服务器提交结构化数据,如API调用中传递JSON格式的请求体。
1、使用 -X POST 明确指定方法,并通过 -H 设置Content-Type头:curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' https://httpbin.org/post。
2、若JSON内容较长,可将数据写入文件后用 @ 引用:curl -X POST -H "Content-Type: application/json" -d @data.json https://httpbin.org/post。
3、添加 -v 参数可查看完整请求与响应过程:curl -v -X POST -H "Content-Type: application/json" -d '{"key":"value"}' https://httpbin.org/post。
三、发送带认证的HTTP请求
当目标接口需要身份验证时,curl支持多种认证方式,包括Basic认证和Bearer Token认证。
1、使用Basic认证时,提供用户名和密码:curl -u "username:password" https://httpbin.org/basic-auth/user/pass。
2、使用Bearer Token认证时,在Authorization头中传入Token:curl -H "Authorization: Bearer abc123xyz" https://httpbin.org/bearer。
3、若需同时发送Cookie,使用 -b 参数:curl -b "sessionid=abc; token=xyz" https://httpbin.org/cookies。
四、发送带自定义Header和超时控制的请求
某些接口要求特定请求头或对响应时间敏感,可通过参数精确控制请求行为。
1、添加任意自定义Header,使用多次 -H 参数:curl -H "X-API-Key: 12345" -H "Accept: application/json" https://httpbin.org/headers。
2、设置连接超时时间为5秒,使用 --connect-timeout 5:curl --connect-timeout 5 https://httpbin.org/delay/3。
3、设置总请求超时为10秒,使用 --max-time 10:curl --max-time 10 https://httpbin.org/delay/8。
五、上传文件至服务器
当接口支持文件上传(如multipart/form-data格式),curl可通过 -F 参数模拟表单提交。
1、上传本地文件file.txt,字段名为“upload”:curl -F "upload=@file.txt" https://httpbin.org/post。
2、同时上传多个文件并附带文本字段:curl -F "file1=@a.jpg" -F "file2=@b.png" -F "description=test" https://httpbin.org/post。
3、指定文件MIME类型,避免服务端解析错误:curl -F "document=@report.pdf;type=application/pdf" https://httpbin.org/post。










