curl 的用法及实际案例记录

@

基础知识

不带参数

不带有任何参数时,curl 就是发出 GET 请求。

curl https://www.cnblogs.com/

上面命令向www.example.com发出 GET 请求,服务器返回的内容会在命令行输出。
在这里插入图片描述

-A

-A参数指定客户端的用户代理标头,即User-Agent。

curl  -A  '' https://google.com/

-b

-b参数用来向服务器发送 Cookie。

 curl -b 'curl=B' https://google.com/

上面命令会生成一个标头Cookie: curl=B,向服务器发送一个名为curl、值为B的 Cookie

-c

-c 参数将服务器设置的 Cookie 写入一个文件

 curl -c cookies.txt https://www.google.com

-d

-d参数用于发送 POST 请求的数据体

 curl -d'login=emma&password=123'-X POST https://google.com/login
# 或者
 curl -d 'login=emma' -d 'password=123' -X POST  https://google.com/login

使用-d参数以后,HTTP 请求会自动加上标头Content-Type : application/x-www-form-urlencoded。并且会自动将请求转为 POST 方法,因此可以省略-X POST

-G

-G参数用来构造 URL 的查询字符串

 curl -G -d 'q=kitties' -d 'count=20' https://google.com/search

上面命令会发出一个 GET 请求,实际请求的 URL 为https://google.com/search?q=kitties&count=20。如果省略--G,会发出一个 POST 请求

-H

-H参数添加 HTTP 请求的标头

  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 数据

-x

-x参数指定 HTTP 请求的代理

 curl -x socks5://james:cats@myproxy.com:8080 https://www.example.com

上面命令指定 HTTP 请求通过myproxy.com:8080的 socks5 代理发出

-X

-X参数指定 HTTP 请求的方法

 curl -X POST https://www.example.com

上面命令对https://www.example.com发出 POST 请求

实际案例

案例场景

spring boot 项目有两个参数,get请求,然后需要在服务器中使用curl命令,测试接口

错误命令

错误命令造成的结果是,接口调用出现参数为空的情况

curl http://localhost:8686/online?pageNo=1&productId=P073-01

正确命令

curl -X GET "http://localhost:8686/online?pageNo=1&productId=P073-01" -H "accept: */*"

正确命令,还可以直接通过swaggerUi获得
在这里插入图片描述

参考链接.

life is beautiful,我是Alon,如果你有问题,欢迎给我留言。更欢迎你的点赞!
原文地址:https://www.cnblogs.com/todayforever/p/12663438.html