curl 笔记
测试工具
可以用nc快速开启一个端口监听, 用来检查curl请求
# 命令格式 nc -l -p [port], 例如
nc -l -p 8080
GET 请求
curl [URL]
# 或者指定请求方式
cURL -X GET [URL]
例如
curl http://127.0.0.1:8768/app/bootup/ping
curl -X GET http://127.0.0.1:8768/app/bootup/ping
GET请求的参数一般放在链接里, 例如
curl -X GET http://127.0.0.1:8768/app/data_import/get?id=1
如果要像POST那样放到 -d 参数中, 则需要加上 -G 参数
-G, --get Put the post data in the URL and use GET
例如
curl -X GET -G -d 'id=1' http://127.0.0.1:8768/app/data_import/get
POST 请求
用 -d 指定参数, 格式默认使用的是 Content-Type: application/x-www-form-urlencoded;charset=UTF-8
cURL -X POST -d "k=v&k2=v2"
如果需要使用 json, 需要用 -H 指定 Content-Type: application/json
curl -X POST -H "Content-Type: application/json" -d '{}' [URL]
例如
curl -X POST -H "Content-Type: application/json" -d '{"page":2, "limit":2}' http://127.0.0.1:8768/app/static_file/list
上传文件
Multipart 文件上传
# 格式, -F可以多个
curl -F key1=value1 -F upload=@localfilename URL
例如
curl -v -F file=@"/home/milton/Downloads/File_28_7.zip" http://127.0.0.1/app/static_file/upload
curl -XPOST -F "k=v" -F "file=@1112002.png" http://localhost:8080/home
如果要上传多个文件, 参数名要唯一, 或者改成数组参数名, 例如
curl -F "f1=@file1.gif" -F "f2=@file2.gif" http://localhost:8080/upload
或者用数组参数名, 例如
curl -F "file[]=@file1.gif" -F "file[]=@file2.gif" http://localhost/upload
全局参数
带错误输出的安静模式 -sS
-s, --silent
Silent or quiet mode. Don't show progress meter or error mes‐
sages. Makes Curl mute.
-S, --show-error
When used with -s it makes curl show an error message if it
fails.
只获取响应头, 用于只需要判断200的场景
-I, --head
(HTTP/FTP/FILE) Fetch the HTTP-header only! HTTP-servers feature
the command HEAD which this uses to get nothing but the header
of a document. When used on an FTP or FILE file, curl displays
the file size and last modification time only.
显示完整请求和响应 -v
例如
curl -v -F file=@"/home/milton/Downloads/File_28_7.zip" http://127.0.0.1:8768/app/static_file/upload
* Trying 127.0.0.1:8768...
* TCP_NODELAY set
* Connected to 127.0.0.1 (127.0.0.1) port 8768 (#0)
> POST /app/static_file/upload HTTP/1.1
> Host: 127.0.0.1:8768
> User-Agent: curl/7.68.0
> Accept: */*
> Content-Length: 291760
> Content-Type: multipart/form-data; boundary=------------------------6e7d753a255e8137
> Expect: 100-continue
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 100
* We are completely uploaded and fine
* Mark bundle as not supporting multiuse
< HTTP/1.1 200
< Vary: Origin
< Vary: Access-Control-Request-Method
< Vary: Access-Control-Request-Headers
< Content-Type: application/json
< Transfer-Encoding: chunked
< Date: Thu, 26 Jan 2023 13:16:50 GMT
<
* Connection #0 to host 127.0.0.1 left intact
{"code":0,"message":"success","data":1}