Linux中使用CURL模拟网络请求

Linux中使用CURL模拟网络请求

GET请求

1
2
3
4
@GetMapping("/demo1")
public String demo1(String name, String age) {
return "demo01 => name = " + name + " age = " + age;
}
1
2
3
4
# -G GET请求
# -d 表单参数
curl localhost:8080/demo1 -G -d "name=Andu&age=20"
demo01 => name = Andu age = 20

POST表单请求

1
2
3
4
@PostMapping("/demo2")
public String demo2(String name, String age) {
return "demo02 => name = " + name + " age = " + age;
}
1
2
3
# 默认则为POST请求
curl localhost:8080/demo2 -d "name=Andu&age=20"
demo02 => name = Andu age = 20

文件上传请求

1
2
3
4
@PostMapping("/demo3")
public String demo3(String name,MultipartFile file) {
return "dem03 => name = " + name + " file = " + file.getOriginalFilename();
}
1
2
3
# 模拟http表单提交数据
curl localhost:8080/demo3 -F "name=submit" -F "file=@C:\\Users\\BPDBSIR\\Desktop\\cmd.php"
dem03 => name = submit file = cmd.php

POST/JSON请求

1
curl -l -H "Content-type: application/json" -X POST -d '{"phone":"13521389587","password":"test"}' URL

文件下载请求

1
curl http://1.15.235.91:8000/Bad.zip -O

发送Cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
curl URL --cookie "xxx"


# 将cookie另存为一个文件,使用--cookie-jar
curl URL --cookie-jar cookie_file


# -b 参数用来向服务器发送 Cookie
curl -b 'foo=bar' https://taobao.com
# 上面命令会生成一个标头Cookie: foo=bar,向服务器发送一个名为foo、值为bar的 Cookie


curl -b 'foo1=bar' -b 'foo2=baz' https://taobao.com
# 上面命令发送两个 Cookie。

curl -b cookies.txt https://www.taobao.com
# 上面命令读取本地文件 cookies.txt,里面是服务器设置的 Cookie(参见-c参数),将其发送到服务器。

自定义请求头

1
2
3
4
5
6
7
8
9
curl -H 'Accept-Language: en-US' https://google.com
# 上面命令添加 HTTP 标头 Accept-Language: en-US。

curl -H 'Accept-Language: en-US' -H 'Secret-Message: xyzzy' https://google.com
# 上面命令添加两个 HTTP 标头。


curl -d '{"login": "emma", "pass": "123"}' -H 'Content-Type: application/json' https://google.com/login
# 上面命令添加 HTTP 请求的标头是 Content-Type: application/json,然后用 -d 参数发送 JSON 数据。

设置用户代理字符串

有些网站访问会提示只能使用IE浏览器来访问,这是因为这些网站设置了检查用户代理,可以使用curl把用户代理设置为IE,这样就可以访问了。使用–user-agent或者-A选项:

1
2
curl URL --user-agent "Mozilla/5.0"
curl URL -A "Mozilla/5.0"

其他HTTP头部信息也可以使用curl来发送,使用-H”头部信息” 传递多个头部信息,例如:

1
curl -H "Host:URL" -H "accept-language:zh-cn" URL

Linux中使用CURL模拟网络请求

https://xiaoyes.cn/post/2022-05-01-curl/

作者

路远

发布于

2022-05-01

更新于

2023-04-21

许可协议