用curl模拟http请求

curl 是利用 url 规则在命令行下工作的工具。我们可以通过它来测试和模拟链接。

比如简单的用 curl 查看自己的 ip 地址:

1
2
3
4
5
6
7
8
9
10
➜  ~ curl cip.cc
IP : 222.***.***.142
地址 : 中国 湖南 长沙
运营商 : 电信

数据二 : 湖南省长沙市 | 电信

数据三 : 中国湖南省长沙市 | 电信

URL : http://www.cip.cc/222.***.***.142

简单来说,可以用它在命令行发起请求。

HTTP 请求

GET

语法:curl protocol://address:port/url?args

1
2
➜  ~ curl api.laravel.local/person?id=2
{"message":"Token\u5df2\u8fc7\u671f","data":[],"errorCode":10003,"requestUrl":"person"}%

POST

语法:curl -d "args" "protocol://address:port/url"
注意:记得参数加引号

1
2
➜  ~ curl -d "mobile=10112345678&password=12345678" "symfony.local/token/user"
{"message":"mobile is not valid.","errorCode":10000,"data":[],"requestUrl":"\/token\/user"}%

PUT | PATCH | DELETE

需要使用其他协议的时候加上-X且在后面指明你要用的协议。

1
2
➜  ~ curl -X PUT "symfony.local/index/index" -d "mobile=15512345678"
{"message":"OK","errorCode":0,"data":{"mobile":"15512345678"},"requestUrl":"\/index\/index"}%

如果你的参数是放在 body 里面的 json 格式数据话,需要设置请求头

1
2
➜  ~ curl -H "Content-Type:application/json" -X PATCH -d '{"mobile":"14412345678"}' symfony.local/index/three
{"message":"OK","errorCode":0,"data":{"mobile":"14412345678"},"requestUrl":"\/index\/three"}%

如果你想查看完整的请求信息加上 -v 类似这样用的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
➜  ~ curl -v -X DELETE "symfony.local/index/second?mobile=15212345678"
* Trying ::1...
* TCP_NODELAY set
* Connected to symfony.local (::1) port 80 (#0)
> DELETE /index/second?mobile=15212345678 HTTP/1.1
> Host: symfony.local
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Sat, 26 Oct 2019 05:27:00 GMT
< Server: Apache
< X-Powered-By: PHP/7.2.14
< Cache-Control: no-cache, private
< X-Robots-Tag: noindex
< Content-Length: 93
< Content-Type: application/json
<
* Connection #0 to host symfony.local left intact
{"message":"OK","errorCode":0,"data":{"mobile":"15212345678"},"requestUrl":"\/index\/second"}%

下载

1
2
➜  ~ curl https://jaychoumylove.github.io/images/avator@slzs.jpg -o 1.jpg --progress
######################################################################## 100.0%

关于更多 curl 的信息可以查看curl 命令_Linux curl 命令用法详解

enjoy and happy coding!