使用curl

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

curl支持的协议有很多,比如HTTP、HTTPS、WS、WSS等,本文以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-Type为multipart/form-data。
shell 复制代码
$ curl -X POST localhost:8080/upload \
> -F "upload=@/Users/path/上传用的文件.txt"
1 files uploaded!
相关推荐
Lsetea23 天前
curl指定--tlsv1.2仍连接TLS1.3:最低版本与tls-max排查
linux·https·ssl证书·curl·tls
Lsetea23 天前
curl访问HTTPS报47 Too many redirects:重定向循环与max-redirs排查
linux·http·https·ssl证书·curl
Lsetea24 天前
curl下载HTTPS正文是乱码:--compressed与Content-Encoding分层排查
linux·http·https·ssl证书·curl
Lsetea25 天前
curl下载HTTPS文件报23:证书验证成功与本地写入失败分层排查
linux·https·shell·ssl证书·curl
Lsetea25 天前
curl访问HTTPS返回304却没有正文:条件请求、缓存与证书验收排查
linux·http·https·ssl证书·curl
Lsetea1 个月前
curl -I检查HTTPS返回405:HEAD、GET与证书验收分层排查
linux·http·https·ssl证书·curl
Lsetea1 个月前
curl访问HTTPS报28 Operation timed out:连接超时与总超时分层排查
运维·https·ssl证书·curl·tls
Lsetea1 个月前
curl设置SSL_CERT_FILE仍报60:CURL_CA_BUNDLE与CA路径优先级排查
linux·https·ssl证书·openssl·curl
Lsetea1 个月前
curl走HTTPS代理报SSL证书错误:proxy-cacert与cacert双层信任排查
linux·https·ssl证书·curl·代理服务器
Lsetea1 个月前
curl报91 No OCSP response received:cert-status与OCSP装订排查
https·ssl证书·openssl·curl·ocsp