curl 指令

勿以恶小而为之,勿以善小而不为---- 刘备

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

image.png

传入一个参数

 @RequestMapping("/getTwo")
    public String getTwo(String name) {
        return "一个普通的Get请求,名称是:"+name;
    }
curl http://localhost:8082/getTwo?name=岳建立

image.png

如果传入的参数有空格 等信息, 如 name = 岳建立 程序员

-- 错误
curl http://localhost:8082/getTwo?name=岳建立  程序员

-- 正确
curl http://localhost:8082/getTwo?name="岳建立  程序员"


image.png

传入多个参数时

    @RequestMapping("/getThree")
    public String getThree(String name,String sex) {
        return "一个普通的Get请求,名称是:"+name+",性别是:"+sex;
    }
-- 错误 
curl http://localhost:8082/getThree?name=yjl&sex=male

image.png

应该使用:

curl http://localhost:8082/getThree?name=yjl"&"sex=male

image.png

在 linux 下也是可以运行的.

image.png

linux 环境下 转码 处理

 curl --data-urlencode "name=岳建立 222" --data-urlencode "sex=男"  http://192.168.100.52:8082/getThree

image.png

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/岳建立/男   

image.png

传入请求头 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=

image.png

可以使用 -Headers @{“key”=“value”} 的形式

不传入请求头时:

curl http://localhost:8082/getFive?name=岳建立"&"sex=

image.png

传入请求头,但是请求头内容错误

curl -Headers @{"Authorization"="abcd3333"} http://localhost:8082/getFive?name=岳建立"&"sex=

image.png

传入正确的请求头

 curl -Headers @{"Authorization"="abcd"} http://localhost:8082/getFive?name=岳建立"&"sex=

image.png

在 linux 下 是错误的
image.png

获取请求头信息:

 @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

image.png

linux 追加 -H

curl http://192.168.100.52:8082/getSix -H "Authorization: abcd" -H "Referer: www"

image.png

是可以获取到请求头内容的。

设置 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 的形式

image.png

需要添加请求头 -H “Content-Type: application/json”

curl -H "Content-Type: application/json" -X POST -d '{"name":"岳建立","sex":"男"}' "http://192.168.100.52:8082/postOne"

image.png

一定要注意, 传入的参数的 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"

image.png

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 的文件位置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

两个蝴蝶飞

你的鼓励,是老蝴蝶更努力写作的

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值