勿以恶小而为之,勿以善小而不为---- 刘备
curl 是常用的命令行工具,用来请求 Web 服务器。
它的名字就是客户端(client)的 URL 工具的意思。
它的功能非常强大,命令行参数多达几十种
我们后端开发者, 可以在用户环境上没有 Postman, ApiFox 这样的请求工具时,使用 curl 进行模拟请求使用。
这个指令 curl 在 cmd (Windows) , PowerShell (Windows) 和 Linux 环境上有一些区别。
项目端口号是 80 , ip 是 127.0.0.1 (192.168.100.52)
Get 请求
普通请求
@RequestMapping("/getOne")
public String getOne() {
return "一个普通的Get请求";
}
curl http://localhost:8082/getOne
传入一个参数
@RequestMapping("/getTwo")
public String getTwo(String name) {
return "一个普通的Get请求,名称是:"+name;
}
curl http://localhost:8082/getTwo?name=岳建立
如果传入的参数有空格 等信息, 如 name = 岳建立 程序员
-- 错误
curl http://localhost:8082/getTwo?name=岳建立 程序员
-- 正确
curl http://localhost:8082/getTwo?name="岳建立 程序员"
传入多个参数时
@RequestMapping("/getThree")
public String getThree(String name,String sex) {
return "一个普通的Get请求,名称是:"+name+",性别是:"+sex;
}
-- 错误
curl http://localhost:8082/getThree?name=yjl&sex=male
应该使用:
curl http://localhost:8082/getThree?name=yjl"&"sex=male
在 linux 下也是可以运行的.
linux 环境下 转码 处理
curl --data-urlencode "name=岳建立 222" --data-urlencode "sex=男" http://192.168.100.52:8082/getThree
pathvariable 注解接收参数
@RequestMapping("/getFour/{name}/{sex}")
public String getFour(@PathVariable("name") String name, @PathVariable("sex") String sex) {
return "一个普通的 path variable 请求,名称是:"+name+",性别是:"+sex;
}
curl http://localhost:8082/getFour/岳建立/男
传入请求头 Authorization 等
@RequestMapping("/getFive")
public String getFive(String name, String sex, HttpServletRequest httpServletRequest) {
// 获取请求头
String authorization = httpServletRequest.getHeader("Authorization");
if (!StringUtils.hasText(authorization)){
return "未传入请求头 Authorization";
}
if (!"abcd".equals(authorization)){
return "传入了错误的请求头";
}
return "一个普通的 path variable 请求,名称是:"+name+",性别是:"+sex;
}
linux 和 shell 下传入 这样的命令是报错的
-- 错误
curl -H "Authorization=abcd" http://localhost:8082/getFive?name=岳建立"&"sex=男
可以使用 -Headers @{“key”=“value”} 的形式
不传入请求头时:
curl http://localhost:8082/getFive?name=岳建立"&"sex=男
传入请求头,但是请求头内容错误
curl -Headers @{"Authorization"="abcd3333"} http://localhost:8082/getFive?name=岳建立"&"sex=男
传入正确的请求头
curl -Headers @{"Authorization"="abcd"} http://localhost:8082/getFive?name=岳建立"&"sex=男
在 linux 下 是错误的
获取请求头信息:
@RequestMapping("/getSix")
public String getSix(HttpServletRequest httpServletRequest) {
// 获取请求头
String authorization = httpServletRequest.getHeader("Authorization");
String referer = httpServletRequest.getHeader("Referer");
return "返回请求头 Authorization :" +authorization+",Referer:"+referer;
}
PowerShell 多个请求头时, 使用 ; 号进行分隔
curl -Headers @{"Authorization"="abcd";"Referer"="www.yueshushu.top"} http://127.0.0.1:8082/getSix
linux 追加 -H
curl http://192.168.100.52:8082/getSix -H "Authorization: abcd" -H "Referer: www"
是可以获取到请求头内容的。
设置 Referer 也可以使用 -e 参数
[root@lb02 ~]# curl http://192.168.100.52:8082/getSix
-H "Authorization: abcd" -e "www.yueshushu.top"
返回请求头 Authorization :abcd,Referer:www.yueshushu.top[root@lb02 ~]#
Post 请求
User.java
@Data
public class User implements Serializable {
private String name;
private String sex;
}
linux 下 简单 post
@PostMapping("/postOne")
public String postOne(@RequestBody User user) {
return "一个普通的 post 请求,名称是:"+ user.getName()+",性别是:"+ user.getSex();
}
-X 指定请求的方式 ,如 -X POST -X DELETE -X PUT
-d 指定参数, 传入的是 json 形式的字符串
先使用 linux 进行演示
curl -X POST -d '{"name":"岳建立","sex":"男"}' http://localhost:8082/postOne
进行请求, 说格式不正确, 需要用 application-json 的形式
需要添加请求头 -H “Content-Type: application/json”
curl -H "Content-Type: application/json" -X POST -d '{"name":"岳建立","sex":"男"}' "http://192.168.100.52:8082/postOne"
一定要注意, 传入的参数的 key 也要用 “” 括起来。
-d ‘{“name”:“岳建立”,“sex”:“男”}’ 不能写成 -d ‘{name:“岳建立”,“sex”:“男”}’
linux 下 携带请求头的 Post
@PostMapping("/postTwo")
public String postTwo(@RequestBody User user,HttpServletRequest httpServletRequest) {
// 获取请求头
String authorization = httpServletRequest.getHeader("Authorization");
if (!StringUtils.hasText(authorization)){
return "未传入请求头 Authorization";
}
if (!"abcd".equals(authorization)){
return "传入了错误的请求头";
}
return "一个普通的 post 请求,名称是:"+ user.getName()+",性别是:"+ user.getSex();
}
需要再传入一个请求头 -H “Authorization:abcd”
[root@mail ~]# curl -H "Content-Type: application/json" -X POST -d '{"name":"岳建立","sex":"男"}' "http://192.168.100.52:8082/postTwo"
未传入请求头 Authorization[root@mail ~]#
[root@mail ~]# curl -H "Content-Type: application/json" -H "Authorization:abcded" -X POST -d '{"name":"岳建立","sex":"男"}' "http://192.168.100.52:8082/postTwo"
传入了错误的请求头[root@mail ~]#
[root@mail ~]#
[root@mail ~]# curl -H "Content-Type: application/json" -H "Authorization:abcd" -X POST -d '{"name":"岳建立","sex":"男"}' "http://192.168.100.52:8082/postTwo"
一个普通的 post 请求,名称是:岳建立,性别是:男[root@mail ~]#
PowerShell 使用 Post 请求
参考链接: https://www.jianshu.com/p/1bcf857eb876
-- 定义url
$uri = 'http://192.168.100.52:8082/postTwo'
-- 传入参数
$hash =@{"name" = "yjl";"sex" = "male";}
-- 定义请求头
$headers = @{"Authorization"="abcd";"Content-Type"="application/json"}
-- 参数转换
$JSON = $hash | convertto-json
-- 进行请求
curl -Headers $headers -uri $uri -Method POST -Body $JSON
PS D:\curl> $uri = 'http://192.168.100.52:8082/postTwo'
PS D:\curl>
PS D:\curl> $hash =@{"name" = "yjl";"sex" = "male";}
PS D:\curl> $headers = @{"Authorization"="abcd";"Content-Type"="application/json"}
PS D:\curl> $JSON = $hash | convertto-json
PS D:\curl> curl -Headers $headers -uri $uri -Method POST -Body $JSON
StatusCode : 200
StatusDescription :
Content : 一个普通的 post 请求,名称是:yjl,性别是:male
RawContent : HTTP/1.1 200
Content-Length: 56
Content-Type: text/plain;charset=UTF-8
Date: Mon, 28 Nov 2022 06:54:16 GMT
一个普通的 post 请求,名称是:yjl,性别是:male
Forms : {}
Headers : {[Content-Length, 56], [Content-Type, text/plain;charset=UTF-8], [Date, Mon, 28 Nov 2022 06:54:16 GMT]}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 56
PS D:\curl>
如果内容过长 或者只要内容的话, 可以使用 | Select -ExpandProperty Content
curl -Headers $headers -uri $uri -Method POST -Body $JSON | Select -ExpandProperty Content
PS D:\curl> curl -Headers $headers -uri $uri -Method Post -Body $JSON | Select -ExpandProperty Content
一个普通的 post 请求,名称是:yjl,性别是:male
Put 请求
@PutMapping("/putTwo")
public String putTwo(@RequestBody User user,HttpServletRequest httpServletRequest) {
// 获取请求头
String authorization = httpServletRequest.getHeader("Authorization");
if (!StringUtils.hasText(authorization)){
return "未传入请求头 Authorization";
}
if (!"abcd".equals(authorization)){
return "传入了错误的请求头";
}
return "一个普通的 put 请求,名称是:"+ user.getName()+",性别是:"+ user.getSex();
}
PS D:\curl> $uri = 'http://192.168.100.52:8082/putTwo'
PS D:\curl>
PS D:\curl> $hash =@{"name" = "yjl";"sex" = "male";}
PS D:\curl> $headers = @{"Authorization"="abcd";"Content-Type"="application/json"}
PS D:\curl> $JSON = $hash | convertto-json
PS D:\curl> curl -Headers $headers -uri $uri -Method PUT -Body $JSON
StatusCode : 200
StatusDescription :
Content : 一个普通的 put 请求,名称是:yjl,性别是:male
RawContent : HTTP/1.1 200
Keep-Alive: timeout=60
Connection: keep-alive
Content-Length: 55
Content-Type: text/plain;charset=UTF-8
Date: Mon, 28 Nov 2022 07:00:50 GMT
一个普通的 put 请求,名称是:yjl,性别是:male
Forms : {}
Headers : {[Keep-Alive, timeout=60], [Connection, keep-alive], [Content-Length, 55], [Content-Type, text/plain;charset=UTF-8]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 55
PS D:\curl>
Delete 请求
@DeleteMapping("/deleteTwo")
public String deleteTwo(@RequestBody User user,HttpServletRequest httpServletRequest) {
// 获取请求头
String authorization = httpServletRequest.getHeader("Authorization");
if (!StringUtils.hasText(authorization)){
return "未传入请求头 Authorization";
}
if (!"abcd".equals(authorization)){
return "传入了错误的请求头";
}
return "一个普通的 delete 请求,名称是:"+ user.getName()+",性别是:"+ user.getSex();
}
PS D:\curl> $uri = 'http://192.168.100.52:8082/deleteTwo'
PS D:\curl>
PS D:\curl> $hash =@{"name" = "yjl";"sex" = "male";}
PS D:\curl> $headers = @{"Authorization"="abcd";"Content-Type"="application/json"}
PS D:\curl> $JSON = $hash | convertto-json
PS D:\curl> curl -Headers $headers -uri $uri -Method Delete -Body $JSON
StatusCode : 200
StatusDescription :
Content : 一个普通的 delete 请求,名称是:yjl,性别是:male
RawContent : HTTP/1.1 200
Keep-Alive: timeout=60
Connection: keep-alive
Content-Length: 58
Content-Type: text/plain;charset=UTF-8
Date: Mon, 28 Nov 2022 07:02:34 GMT
一个普通的 delete 请求,名称是:yjl,性别是:male
Forms : {}
Headers : {[Keep-Alive, timeout=60], [Connection, keep-alive], [Content-Length, 58], [Content-Type, text/plain;charset=UTF-8]...}
Images : {}
InputFields : {}
Links : {}
ParsedHtml : mshtml.HTMLDocumentClass
RawContentLength : 58
PS D:\curl>
将数据保存到文件里面
使用 -outfile “文件路径”
curl -Headers $headers -uri $uri -Method Post -Body $JSON -outfile "D:\\post.txt"
linux 使用 -o 路径
[root@mail ~]# curl -H "Content-Type: application/json" -H "Authorization:abcd" -X POST -d '{"name":"岳建立","sex":"男"}' "http://192.168.100.52:8082/postTwo" -o /usr/post.txt
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 93 100 61 100 32 661 346 --:--:-- --:--:-- --:--:-- 663
[root@mail ~]# cat /usr/post.txt
一个普通的 post 请求,名称是:岳建立,性别是:男[root@mail ~]#
上传文件
请求上传文件
-F 进行上传文件
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file) {
return "上传文件成功,文件名是:"+file.getOriginalFilename();
}
-F ‘file=@/usr/post.txt;’ 其中 file 为 key , @后面加路径
[root@mail ~]# curl -H "Content-Type: multipart/form-data" -F 'file=@/usr/post.txt;' -X POST "http://192.168.100.52:8082/uploadFile"
上传文件成功,文件名是:post.txt[root@mail ~]#
curl 对 FTP 的支持
展示目录
curl ftp://用户名:密码@www.yueshushu.top:21
[root@mail usr]# curl ftp://密码:用户名@www.yueshushu.top:21
-rw-r--r-- 1 0 0 2202 Sep 15 09:19 item.csv
下载文件
curl ftp://www.yueshushu.top/item.csv –u 用户名:密码 -o item.csv
[root@mail usr]# curl ftp://密码:testftp@www.yueshushu.top:21
-rw-r--r-- 1 0 0 2202 Sep 15 09:19 item.csv
[root@mail usr]# curl ftp://www.yueshushu.top/item.csv –u 密码:testftp -o item.csv
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- 0:00:02 --:--:-- 0
curl: (67) Access denied: 530
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
上传文件
curl –u 用户名:密码 -T post.txt ftp://www.yueshushu.top/
[root@mail usr]# curl –u testftp:密码 -T post.txt ftp://www.yueshushu.top/
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
60 154 100 93 0 0 150 0 --:--:-- --:--:-- --:--:-- 150
<html><body><h1>403 Forbidden</h1>
Request forbidden by administrative rules.
</body></html>
curl: (67) Access denied: 530
[root@mail usr]#
不太重要的属性
-A User-Agent
curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36" http://localhost:8082/getOne
-b 设置 cookie
$ curl -b 'foo=bar' http://localhost:8082/getOne
会生成一个 Cookie, foo = bar
–limit-rate 设置带宽
$ curl --limit-rate 200k http://localhost:8082/getOne
带宽设置在 每秒 200 k
-v 展示全部内容
curl --limit-rate 200k -v http://192.168.100.52:8082/getOne
[root@mail ~]# curl --limit-rate 200k -v http://192.168.100.52:8082/getOne
* About to connect() to 192.168.100.52 port 8082 (#0)
* Trying 192.168.100.52...
* Connected to 192.168.100.52 (192.168.100.52) port 8082 (#0)
> GET /getOne HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 192.168.100.52:8082
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: text/plain;charset=UTF-8
< Content-Length: 24
< Date: Mon, 28 Nov 2022 07:50:24 GMT
<
* Connection #0 to host 192.168.100.52 left intact
一个普通的Get请求[root@mail ~]#
Curl 完整指令
# 调试类
-v, --verbose 输出信息
-q, --disable 在第一个参数位置设置后 .curlrc 的设置直接失效,这个参数会影响到 -K, --config -A, --user-agent -e, --referer
-K, --config FILE 指定配置文件
-L, --location 跟踪重定向 (H)
# CLI显示设置
-s, --silent Silent模式。不输出任务内容
-S, --show-error 显示错误. 在选项 -s 中,当 curl 出现错误时将显示
-f, --fail 不显示 连接失败时HTTP错误信息
-i, --include 显示 response的header (H/F)
-I, --head 仅显示 响应文档头
-l, --list-only 只列出FTP目录的名称 (F)
-#, --progress-bar 以进度条 显示传输进度
# 数据传输类
-X, --request [GET|POST|PUT|DELETE|…] 使用指定的 http method 例如 -X POST
-H, --header <header> 设定 request里的header 例如 -H "Content-Type: application/json"
-e, --referer 设定 referer (H)
-d, --data <data> 设定 http body 默认使用 content-type application/x-www-form-urlencoded (H)
--data-raw <data> ASCII 编码 HTTP POST 数据 (H)
--data-binary <data> binary 编码 HTTP POST 数据 (H)
--data-urlencode <data> url 编码 HTTP POST 数据 (H)
-G, --get 使用 HTTP GET 方法发送 -d 数据 (H)
-F, --form <name=string> 模拟 HTTP 表单数据提交 multipart POST (H)
--form-string <name=string> 模拟 HTTP 表单数据提交 (H)
-u, --user <user:password> 使用帐户,密码 例如 admin:password
-b, --cookie <data> cookie 文件 (H)
-j, --junk-session-cookies 读取文件中但忽略会话cookie (H)
-A, --user-agent user-agent设置 (H)
# 传输设置
-C, --continue-at OFFSET 断点续转
-x, --proxy [PROTOCOL://]HOST[:PORT] 在指定的端口上使用代理
-U, --proxy-user USER[:PASSWORD] 代理用户名及密码
# 文件操作
-T, --upload-file <file> 上传文件
-a, --append 添加要上传的文件 (F/SFTP)
# 输出设置
-o, --output <file> 将输出写入文件,而非 stdout
-O, --remote-name 将输出写入远程文件
-D, --dump-header <file> 将头信息写入指定的文件
-c, --cookie-jar <file> 操作结束后,要写入 Cookies 的文件位置