使用curl

curl 是一种使用URL从服务器获取数据或者向服务器传输数据的工具。在做一些简单的请求测试的时候可以直接在命令行执行curl指令,而不用打开Postman之类的App,减少一些操作步骤。

curl支持的协议有很多,比如HTTPHTTPSWSWSS等,本文以HTTP协议的URL为例说明一些用法。

  1. 简单的GET请求:
shell 复制代码
$ curl http://localhost:8080/hello
hello world!
  1. 使用-X--request)指定请求方法:
shell 复制代码
$ curl -X POST localhost:8080/user/login

不使用-X默认是GET请求。

  1. 使用-i--include)将响应头中的数据打印出来:
shell 复制代码
$ curl -i -X GET "localhost:8080/echo?name=孙悟空&address=花果山水帘洞"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Thu, 14 Dec 2023 13:32:03 GMT
Content-Length: 60
​
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}                                         
  1. 使用-v--verbose)打印出一些冗长的信息,调试的时候可以使用:
shell 复制代码
curl -v localhost:8080/孙悟空/987fbc97-4bed-5078-9f07-9141ba07c9f3
*   Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /%e5%ad%99%e6%82%9f%e7%a9%ba/987fbc97-4bed-5078-9f07-9141ba07c9f3 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.88.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Fri, 15 Dec 2023 03:13:17 GMT
< Content-Length: 73
< 
* Connection #0 to host localhost left intact
{"data":{"id":"987fbc97-4bed-5078-9f07-9141ba07c9f3","name":"孙悟空"}}
  1. 使用-d--data)在POST请求中携带数据:
shell 复制代码
$ curl -X POST -d '{"name": "孙悟空", "address": "花果山水帘洞"}' localhost:8080/echo \
>  -H "Content-Type:application/json"
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}

或者:

shell 复制代码
$ curl -X POST -d "name=孙悟空&address=花果山水帘洞" localhost:8080/echo
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}

因为GET的数据是在url中携带的,所以直接这样请求:

shell 复制代码
$ curl -i -X GET "localhost:8080/echo?name=孙悟空&address=花果山水帘洞"
  1. 使用-H--header) 设置请求头:
shell 复制代码
$ curl -X POST -d '{"name": "孙悟空", "address": "花果山水帘洞"}' localhost:8080/echo \
>  -H "Content-Type:application/json"
{"data":{"name":"孙悟空","address":"花果山水帘洞"}}
  1. -F--form)模拟用户按下提交按钮后填写的表单,使用-F后的Content-Typemultipart/form-data
shell 复制代码
$ curl -X POST localhost:8080/upload \
> -F "upload=@/Users/path/上传用的文件.txt"
1 files uploaded!
相关推荐
云游云记4 天前
php cURL 常用参数详解与实用指南
开发语言·php·curl
sxy_976111 天前
AX86u官方固件温度监控(CPU,WIFI芯片)
python·docker·curl·nc·nas·温度·ax86u
码农爱学习14 天前
curl使用读回调来分块上报文件
curl
为java加瓦19 天前
Linux 系统磁盘空间清理指南:安全释放存储空间的完整方案
linux·curl
太空眼睛23 天前
【MCP】使用SpringBoot基于Streamable-HTTP构建MCP-Server
spring boot·sse·curl·mcp·mcp-server·spring-ai·streamable
风清扬_jd1 个月前
libcurl 开启https一键编译指南【MT方式】
c++·https·curl
码农爱学习1 个月前
curl编程实例-上传文件
curl
龚建波2 个月前
记录:vcpkg清单模式安装指定版本的curl和OpenSSL
openssl·curl·vcpkg
YouEmbedded2 个月前
解码ARM 开发板 OpenSSL+cURL 交叉编译与 HTTPS 配置
https·openssl·curl
大米粥哥哥3 个月前
c++ libcurl报错Send failed since rewinding of the data stream failed【已解决】
开发语言·c++·http·curl·rewind